Compare commits

..

280 Commits
ego ... master

Author SHA1 Message Date
195b717e01
release: 0.2.5
All checks were successful
Tests / Go tests (push) Successful in 49s
Create distribution / Release (push) Successful in 1m6s
Nix / NixOS tests (push) Successful in 1m23s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-20 00:28:48 +09:00
df6fc298f6
migrate to git.gensokyo.uk/security/fortify
All checks were successful
Tests / Go tests (push) Successful in 2m55s
Nix / NixOS tests (push) Successful in 5m10s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-20 00:20:02 +09:00
eae3034260
state: expose aids and use instance id as key
All checks were successful
Tests / Go tests (push) Successful in 39s
Nix / NixOS tests (push) Successful in 3m26s
Fortify state store instances was specific to aids due to outdated design decisions carried over from the ego rewrite. That no longer makes sense in the current application, so the interface now enables a single store object to manage all transient state.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-19 21:36:17 +09:00
5ea7333431
fst: implement app id parser
All checks were successful
Tests / Go tests (push) Successful in 40s
Nix / NixOS tests (push) Successful in 3m8s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-19 18:19:47 +09:00
f796622c35
state: rename simple store implementation
All checks were successful
Tests / Go tests (push) Successful in 42s
Nix / NixOS tests (push) Successful in 3m4s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-19 11:48:48 +09:00
5d25bee786
fortify: remove systemd check
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 3m3s
This is no longer necessary as fortify no longer integrates with external user switchers.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-19 11:14:31 +09:00
b48ece3bb0
acl: use test-managed tmpdir
All checks were successful
Tests / Go tests (push) Successful in 44s
Nix / NixOS tests (push) Successful in 3m7s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-19 11:08:13 +09:00
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
38653c6ab5
release: 0.2.3
All checks were successful
Tests / Go tests (push) Successful in 55s
Create distribution / Release (push) Successful in 1m1s
Nix / NixOS tests (push) Successful in 5m5s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 14:06:17 +09:00
b5cbbeab90
dist: generate distribution tarball
All checks were successful
Tests / Go tests (push) Successful in 46s
Create distribution / Release (push) Successful in 49s
Nix / NixOS tests (push) Successful in 5m9s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 14:02:54 +09:00
c3ba0c3cce
nix: rename nixos test
All checks were successful
Tests / Go tests (push) Successful in 39s
Nix / NixOS tests (push) Successful in 5m0s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 13:02:12 +09:00
b453f70ca2
cmd/fsu: check uid range before syscall
All checks were successful
Tests / Go tests (push) Successful in 43s
Nix / NixOS tests (push) Successful in 5m0s
This limits potential exploits to the fortify uid range.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 13:01:36 +09:00
c2b178e626
xcb: refactor and clean up
All checks were successful
Tests / Go tests (push) Successful in 45s
Nix / NixOS tests (push) Successful in 5m2s
No clean way to write Go tests for this package. Will rely on NixOS tests for now.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 12:46:36 +09:00
aeda40fc92
nix: test x11 permissive defaults
All checks were successful
Tests / Go tests (push) Successful in 40s
Nix / NixOS tests (push) Successful in 4m51s
Also invoke glinfo/wayland-info as part of tests.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 12:40:29 +09:00
65dc39956f
workflows: set action names
All checks were successful
Tests / Go tests (push) Successful in 42s
Nix / NixOS tests (push) Successful in 4m33s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 11:12:39 +09:00
35505c8a26
workflows: invoke nix flake checks
All checks were successful
check / nix-flake-check (push) Successful in 4m32s
test / test (push) Successful in 37s
Integration tests are implemented as nix flake checks.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 10:49:43 +09:00
3f993021f8
nix: permissive defaults nixos test
All checks were successful
test / test (push) Successful in 37s
Adapted from nixos sway integration tests.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 22:56:10 +09:00
4d3bd5338f
nix: implement flake checks
All checks were successful
test / test (push) Successful in 36s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 20:54:28 +09:00
138666d753
nix: skip acl test
All checks were successful
test / test (push) Successful in 39s
The nix build environment does not support ACLs.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 19:29:01 +09:00
f4628e181b
acl: create test file in tmpdir
All checks were successful
test / test (push) Successful in 37s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 18:58:09 +09:00
c8a90666c5
acl: refactor and clean up
All checks were successful
test / test (push) Successful in 37s
Move all C code to c.go, switch to pkg-config, set up finalizer for acl.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 18:27:19 +09:00
ee41b37606
acl: add tests
All checks were successful
test / test (push) Successful in 37s
These tests test UpdatePerm correctness by parsing getfacl output.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-16 16:00:31 +09:00
e3f1d7ba60
release: 0.2.2
All checks were successful
release / release (push) Successful in 44s
test / test (push) Successful in 35s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-07 21:47:22 +09:00
39e3ac3ccd
nix: require /etc/userdb nix-daemon
All checks were successful
test / test (push) Successful in 36s
There seems to be some kind of credential caching in nix-daemon.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-07 21:07:57 +09:00
33c95b80ca
cmd/fuserdb: rename home directories
All checks were successful
test / test (push) Successful in 36s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-07 20:23:46 +09:00
40cc8a68d1
nix: rename home directories
All checks were successful
test / test (push) Successful in 38s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-07 20:15:37 +09:00
f773c92411
system: prevent duplicate Wayland op
All checks were successful
test / test (push) Successful in 36s
Wayland is implemented as an Op to enforce dependency and cleanup, its implementation does not allow multiple instances on a single sys object, nor would doing that make any sense.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-07 19:45:37 +09:00
16ab734fcd
update README document
All checks were successful
test / test (push) Successful in 37s
A lot of this information is no longer true since fsu. Remove them for now and write up proper documentation later.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 17:04:36 +09:00
cc816a1aaa
proc: cleaner extra files
All checks were successful
test / test (push) Successful in 37s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 16:05:04 +09:00
b3ef53b193
app: integrate security-context-v1
All checks were successful
test / test (push) Successful in 37s
Should be able to get rid of XDG_RUNTIME_DIR share after this.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 04:25:33 +09:00
8d0573405a
helper/bwrap: implement sync fd
All checks were successful
test / test (push) Successful in 38s
This is required by wayland security-context-v1.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 04:21:37 +09:00
38e92edb8e
system/wayland: integrate security-context-v1
All checks were successful
test / test (push) Successful in 37s
Had to pass the sync fd through sys. The rest are just part of a standard Op.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 04:20:15 +09:00
2d606b1f4b
wl: implement security-context-v1
All checks were successful
test / test (push) Successful in 38s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 04:15:13 +09:00
1b5b089c78
fortify: rename --dbus-id to --id
All checks were successful
test / test (push) Successful in 19s
This value is no longer specific to D-Bus defaults.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 03:26:09 +09:00
6b8ddca7b4
nix: track nixos stable 24.11
All checks were successful
test / test (push) Successful in 25s
Reduce rebuilds during development on my system.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-06 00:44:04 +09:00
95668ac998
nix: expose no_new_session in module
All checks were successful
test / test (push) Successful in 14s
Useful for shells and terminal programs like chat clients.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-28 00:19:06 +09:00
b291f0b710
app: add nixos-based config test case
All checks were successful
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-21 12:13:21 +09:00
3a20b149ce
update README document
All checks were successful
test / test (push) Successful in 26s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-21 11:22:34 +09:00
30b8bce90a
fortify: zsh completion
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-20 01:25:19 +09:00
de0d78daae
release: 0.2.1
All checks were successful
release / release (push) Successful in 1m4s
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 21:03:50 +09:00
6bf33ce507
fortify: use resolved username
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 21:03:09 +09:00
9faf3b3596
app: validate username
All checks were successful
test / test (push) Successful in 23s
This value is used for passwd generation. Bad input can cause very confusing issues. This is not a security issue, however validation will improve user experience.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 21:01:41 +09:00
d99c8b1fb4
release: 0.2.0
All checks were successful
release / release (push) Successful in 44s
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 18:15:09 +09:00
6e4870775f
update README document
All checks were successful
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 18:14:06 +09:00
0a546885e3
nix: update options doc
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 18:12:35 +09:00
653d69da0a
nix: module descriptions
All checks were successful
test / test (push) Successful in 24s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 18:10:57 +09:00
f8256137ae
nix: separate module options from implementation
All checks were successful
test / test (push) Successful in 25s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-19 17:08:22 +09:00
54b47b0315
nix: copy pixmaps directory to share package
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 14:46:08 +09:00
ae2628e57a
cmd/fshim/ipc: install signal handler on shim start
All checks were successful
test / test (push) Successful in 20s
Getting killed at this point will result in inconsistent state.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 13:33:46 +09:00
c026a4b5dc
fortify: permissive defaults resolve home directory from os
All checks were successful
test / test (push) Successful in 21s
When starting with the permissive defaults "run" command, attempt to resolve home directory from os by default and fall back to /var/empty.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 13:01:07 +09:00
748a0ae2c8
nix: wrap program from libexec
All checks were successful
test / test (push) Successful in 24s
This avoids renaming the fortify binary.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 12:58:47 +09:00
8f3f0c7bbf
nix: integrate dynamic users
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 02:49:48 +09:00
05b7dbf066
app: alternative inner home path
All checks were successful
test / test (push) Successful in 24s
Support binding home to an alternative path in the mount namespace.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-18 00:18:21 +09:00
866270ff05
fmsg: add to wg prior to enqueue
All checks were successful
test / test (push) Successful in 27s
Adding after channel write is racy.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-17 23:50:02 +09:00
c1fad649e8
app/start: check for cleanup and abort condition
All checks were successful
test / test (push) Successful in 21s
Dirty fix. Will rewrite after fsu integration complete.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-17 23:41:52 +09:00
b5f01ef20b
app: append # for ChangeHosts message with numerical uid
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-17 23:40:37 +09:00
2e23cef7bb
cmd/fuserdb: generate group entries
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-17 23:31:06 +09:00
6a6d30af1f
cmd/fuserdb: systemd userdb drop-in entries generator
All checks were successful
test / test (push) Successful in 20s
This provides user records via nss-systemd. Static drop-in entries are generated to reduce complexity and attack surface.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-17 02:16:02 +09:00
df33123bd7
app: integrate fsu
All checks were successful
test / test (push) Successful in 21s
This removes the dependency on external user switchers like sudo/machinectl and decouples fortify user ids from the passwd database.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-16 21:19:45 +09:00
1a09b55bd4
nix: remove portal paths from default
All checks were successful
test / test (push) Successful in 27s
Despite presenting itself as a generic desktop integration interface, xdg-desktop portal is highly flatpak-centric and only supports flatpak and snap in practice. It is a significant attack surface to begin with as it is a privileged process which accepts input from unprivileged processes, and the lack of support for anything other than fortify also introduces various information leaks when exposed to fortify as it treats fortified programs as unsandboxed, privileged programs in many cases.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-10 22:24:17 +09:00
9a13b311ac
app/config: rename map_real_uid from use_real_uid
All checks were successful
test / test (push) Successful in 19s
This option only changes mapped uid in the user namespace.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-09 12:01:34 +09:00
45fead18c3
cmd/fshim: set no_new_privs flag
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-09 11:50:56 +09:00
431aa32291
nix: remove absolute Exec paths
All checks were successful
test / test (push) Successful in 26s
Absolute paths set for Exec causes the program to be launched as the privileged user.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-08 02:05:47 +09:00
3962705126
nix: keep fshim and finit names
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 14:59:28 +09:00
ad80be721b
nix: improve start script
All checks were successful
test / test (push) Successful in 23s
Zsh store path in shebang. Replace writeShellScript with writeScript since runtimeShell is not overridable.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 14:09:41 +09:00
f831948bca
release: 0.1.0
All checks were successful
release / release (push) Successful in 28s
test / test (push) Successful in 21s
This release significantly changes the command line interface, and updates the NixOS module to finally produce meaningful sandbox configuration.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 04:37:43 +09:00
2e31b3d3a1
update README document
All checks were successful
test / test (push) Successful in 32s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 04:35:52 +09:00
4d90e73366
nix: generate strict sandbox configuration
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 04:25:15 +09:00
3dfc1fcd56
app: support full /dev access
All checks were successful
test / test (push) Successful in 22s
Also moved /dev/fortify to /fortify since it is impossible to create new directories in /dev from the init namespace and bind mounting its contents has undesirable side effects.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-06 03:49:39 +09:00
89bafd0c22
fortify: root check before command handling
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-05 12:57:03 +09:00
861bb1274f
fortify: override default usage function
All checks were successful
test / test (push) Successful in 23s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-05 00:12:31 +09:00
714818c8aa
fortify: implement cleaner argument structure
All checks were successful
test / test (push) Successful in 24s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-05 00:07:36 +09:00
69cc64ef56
linux: provide access to stdout
All checks were successful
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 22:55:46 +09:00
fc25ac2523
app: separate auto etc from permissive defaults
All checks were successful
test / test (push) Successful in 23s
Populating /etc with symlinks is quite useful even outside the permissive defaults usage pattern.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 22:18:05 +09:00
d909b1190a
app/config: UseRealUID as true in template
All checks were successful
test / test (push) Successful in 24s
The template is based on a Chromium setup, which this workaround was created for.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 19:45:31 +09:00
cfd05b10f1
release: 0.0.11
All checks were successful
release / release (push) Successful in 28s
test / test (push) Successful in 19s
This will be the final release before major command line interface changes. This version is tagged as it contains many fixes that still impacts the permissive defaults usage pattern.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 13:46:47 +09:00
aa067436a7
workflows: build all packages with full ldflags
All checks were successful
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 13:43:57 +09:00
d7df24c999
fmsg: drop messages when msgbuf is full during withhold
All checks were successful
test / test (push) Successful in 20s
Logging functions are not expected to block. This change fixes multiple hangs where more than 64 messages are produced during withhold.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 12:56:19 +09:00
88abcbe0b2
cmd/fsu: remove import of internal package
All checks were successful
test / test (push) Successful in 24s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 12:32:14 +09:00
af15b1c048
app: support mapping target uid as privileged uid in sandbox
All checks were successful
test / test (push) Successful in 40s
Chromium's D-Bus client implementation refuses to work when its getuid call returns a different value than what the D-Bus server is running as. The reason behind this is not fully understood, but this workaround is implemented to support chromium and electron apps. This is not used by default since it has many side effects that break many other programs, like SSH on NixOS.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 03:15:39 +09:00
7962681f4a
app: format mapped uid instead of real uid
All checks were successful
test / test (push) Successful in 19s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-04 00:49:32 +09:00
bfcce3ff75
system/dbus: buffer xdg-dbus-proxy messages
All checks were successful
test / test (push) Successful in 21s
Pointing xdg-dbus-proxy to stdout/stderr makes a huge mess. This change enables app to neatly print out prefixed xdg-dbus-proxy messages after output is resumed.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-03 03:07:02 +09:00
8cd3651bb6
cmd/fshim/ipc: friendly setup timeout message
All checks were successful
test / test (push) Successful in 22s
This message eventually gets returned by the app's Start method, so they should be wrapped to provide a friendly message.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-03 02:03:30 +09:00
422d8e00d5
fortify: replace direct syscall with prctl wrapper
All checks were successful
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-02 17:00:25 +09:00
584732f80a
cmd: shim and init into separate binaries
All checks were successful
test / test (push) Successful in 19s
This change also fixes a deadlock when shim fails to connect and complete the setup.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-11-02 03:13:57 +09:00
4b7b899bb3
add package doc comments
All checks were successful
test / test (push) Successful in 19s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 20:57:59 +09:00
563c39c2d9
release: 0.0.10
All checks were successful
release / release (push) Successful in 24s
test / test (push) Successful in 19s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 20:38:10 +09:00
aa1f96eeeb
fsu: check parent executable path
All checks were successful
test / test (push) Successful in 19s
Only allow main program to launch fsu. This change and further checks in the main program reduces attack surface.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 18:52:23 +09:00
431dc095e5
app/start: skip cleanup if shim is nil
All checks were successful
test / test (push) Successful in 19s
Shim is created before any system operation happens.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 14:21:15 +09:00
60e91b9b0f
shim: expose checkPid in constructor
All checks were successful
test / test (push) Successful in 1m44s
This will be supported soon when launching via fsu.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 00:02:55 +09:00
d9cb2a9f2b
fsu: implement simple setuid user switcher
Contains path to fortify, set at compile time, authenticates based on a simple uid range assignment file which also acts as the allow list.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-28 00:02:34 +09:00
09feda3783
fortify: exit if seal returns error
All checks were successful
test / test (push) Successful in 20s
Wait should not be called on an unsealed App.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 23:18:16 +09:00
51e84ba8a5
system/dbus: compare sealed value by string
All checks were successful
test / test (push) Successful in 19s
Stringer method of dbus.Proxy returns a string representation of its args stream when sealed.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 12:09:34 +09:00
7df9d8d01d
system: move sd_booted implementation to os abstraction
This implements lazy loading of the systemd marker (they are not accessed in init and shim) and ensures consistent behaviour when running with a stub.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 12:09:34 +09:00
6d8bcb63f2
release: 0.0.9
All checks were successful
release / release (push) Successful in 27s
test / test (push) Successful in 22s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 01:25:24 +09:00
c7b77d6e5e
fmsg: initialise dequeue prior to withhold/resume
All checks were successful
test / test (push) Successful in 23s
This fixes the hang on resume when no messages were ever printed.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 01:24:30 +09:00
2f34627d37
release: 0.0.8
All checks were successful
release / release (push) Successful in 31s
test / test (push) Successful in 20s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 00:49:50 +09:00
1d6ea81205
shim: user switcher process management struct
All checks were successful
test / test (push) Successful in 19s
This change moves all user switcher and shim management to the shim package and withholds output while shim is alive. This also eliminated all exit scenarios where revert is skipped.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-27 00:46:15 +09:00
ae1a102882
fmsg: support temporarily withholding output
All checks were successful
test / test (push) Successful in 31s
Trying to print to a shared stdout is a terrible idea. This change makes it possible to withhold output for the lifetime of the sandbox.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-26 23:09:32 +09:00
093e99d062
app: separate nixos test cases from tests
All checks were successful
test / test (push) Successful in 20s
Test cases are very long, separating them improves editor performance.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 17:44:29 +09:00
ad7e389eee
app: test app permissive defaults sealing behaviour
All checks were successful
test / test (push) Successful in 20s
This test seals App against a deterministic os stub and checks the resulting sys and bwrap values against known correct ones. The effects of sys and bwrap on the OS and sandbox is deterministic and tested in their own respective packages.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 17:12:13 +09:00
5b249e4a66
system: print number of ops completed at point of failure
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 17:08:21 +09:00
2a348c7f91
system: include more info in ACL Stringer
All checks were successful
test / test (push) Successful in 24s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 16:23:22 +09:00
eb767e7642
app/start: cleaner command not found message
All checks were successful
test / test (push) Successful in 27s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 16:12:18 +09:00
3bfe8dbf5d
internal: ReadDir wrapper return fs.DirEntry
All checks were successful
test / test (push) Successful in 25s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 14:56:29 +09:00
8fa791a2f8
app/seal: symlink /etc entries in permissive default
All checks were successful
test / test (push) Successful in 20s
Fortify overrides /etc/passwd and /etc/group in the sandbox. Bind mounting /etc results in them being replaced when the passwd database is updated on host.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 13:31:57 +09:00
b932ac8260
app/config: support creating symlinks within sandbox
All checks were successful
test / test (push) Successful in 21s
This is already supported by the underlying bwrap helper. This change exposes access to it in Config.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 13:29:01 +09:00
050ffceb27
helper/bwrap: register generic PermConfig types with gob
All checks were successful
test / test (push) Successful in 21s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 13:26:01 +09:00
31350d74e5
shim: kill shim if setup becomes impossible
All checks were successful
test / test (push) Successful in 23s
This prevents a hang when setup faults but the shim keeps waiting on the socket. Setup is automatically aborted when the shim is killed.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 13:19:37 +09:00
3b82cc55de
internal: use fallback paths when XDG_RUNTIME_DIR is not absolute
All checks were successful
test / test (push) Successful in 24s
There are scenarios where XDG_RUNTIME_DIR is set to an empty string or garbage. This check tries to ensure reasonable behaviour in most of those cases.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-25 12:14:57 +09:00
6bc5be7e5a
internal: wrap calls to os standard library functions
All checks were successful
test / test (push) Successful in 19s
This change helps tests stub out and simulate OS behaviour during the sealing process. This also removes dependency on XDG_RUNTIME_DIR as the internal.System implementation provided to App provides a compat directory inside the tmpdir-based share when XDG_RUNTIME_DIR is unavailable.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-23 21:46:21 +09:00
e35c5fe3ed
system: sys comparison method
All checks were successful
test / test (push) Successful in 24s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-23 14:15:13 +09:00
20195ece47
system: return sys in queueing methods
All checks were successful
test / test (push) Successful in 54s
This enables building an instance in a single statement.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-23 12:34:16 +09:00
cafed5f234
shim: abort setup on failed start and process exit
All checks were successful
test / test (push) Successful in 25s
Shim setup listens on a socket in the process share, if shim setup hasn't happened on exit revert will fail. This change makes sure shim setup is aborted on a doomed launch.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-21 21:23:56 +09:00
42e0b168e3
fmsg: produce all output through fmsg
All checks were successful
test / test (push) Successful in 17s
The behaviour of print functions from package fmt is not thread safe. Functions provided by fmsg wrap around Logger methods. This makes prefix much cleaner and makes it easy to deal with future changes to logging.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-21 20:47:02 +09:00
380d1f4585
app: move wayland mediation to shim package
All checks were successful
test / test (push) Successful in 29s
Values used in the Wayland mediation implementation is stored in various struct fields strewn across multiple app structs and checks are messy and confusing. This commit unifies them into a single struct and access it using much better looking methods.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-21 18:46:06 +09:00
133f23e0de
release: 0.0.7
All checks were successful
release / release (push) Successful in 21s
test / test (push) Successful in 11s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-20 19:50:59 +09:00
65af1684e3
migrate to git.ophivana.moe/security/fortify
All checks were successful
test / test (push) Successful in 14s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-20 19:50:13 +09:00
cdda33555c
update README document
We have a highly configurable sandbox now, just not really the Android sandbox.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-20 00:24:50 +09:00
ad0034b09a
app: move app ID to app struct
App ID is inherent to App, and it makes no sense to generate it as part of the app sealing process.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-20 00:22:18 +09:00
1da845d78b
workflows: call apt-get without sudo
Workflow scripts run as root in act-runner containers, so calling sudo is redundant and pointless.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-18 22:56:49 +09:00
55bb348d5f
state: store launch method instead of launcher path
Launcher path is constant for each launch method on the same system.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-18 22:25:09 +09:00
ecce832d93
release: 0.0.6
All checks were successful
release / release (push) Successful in 1m46s
test / test (push) Successful in 1m39s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-18 01:26:42 +09:00
65bd7d18db
app/share: fix order to ensure SharePath before any of its subdirectories
shareTmpdirChild happened to request an ephemeral dir within SharePath and was called before shareRuntime which ensures that path. This commit moves SharePath initialisation to shareSystem and moves shareTmpdirChild into ShareSystem. Further cleanup and tests are desperately needed for the app package but for now this fix will have to do.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-18 01:21:58 +09:00
4ebb98649e
release: 0.0.5
All checks were successful
release / release (push) Successful in 1m26s
test / test (push) Successful in 3m6s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 20:48:41 +09:00
919e5b5cd5
init: start timeout only if reaped PID is the initial process
Fix a very obvious bug introduced in 5401882ed0.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 20:46:48 +09:00
40161c5938
nix: remove fortify package from default devShell
This change makes it possible to start a devShell when tests aren't passing.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 20:35:10 +09:00
679e719f9e
system: tests for all Op implementations except DBus
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 20:28:55 +09:00
064db9f020
system/mkdir: type label in String method
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 16:37:23 +09:00
73a698c7cb
ldd: run ldd with read-only filesystem and unshared net
This is only called on trusted programs, however extra hardening is never a bad idea.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 15:37:27 +09:00
57c1b3eda6
system: handle invalid enablement in String method
Invalid enablement is only caused by bad API usage, however panicking on the spot leaves behind messy state that has to be manually cleaned up.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 14:31:13 +09:00
5401882ed0
init: post initial process death exit timeout
Wait for 5 seconds before printing a message and exiting after picking up the initial process's wait status. This also kills any lingering processes.This behaviour is helpful for applications launched without a terminal attached.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 02:38:24 +09:00
dd78728fb3
workflows: test workflow to run tests every commit
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 00:18:20 +09:00
354c23dd28
workflows: add lines between steps
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-17 00:17:40 +09:00
c21168a741
system: move enablements from state package
This removes the unnecessary import of the state package.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-16 14:38:57 +09:00
084cd84f36
app: port app to use the system package
This commit does away with almost all baggage left over from the Ego port. Error wrapping also got simplified. All API changes happens to be internal which means no changes to main except renaming of the BaseError type.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-16 01:38:59 +09:00
430f1a5b4e
system: isolate app/system into generic implementation
This improves maintainability and extensibility of system operations, makes writing tests for them possible, and operations now apply and revert in order, instead of being bunched up into their own categories.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-16 01:31:23 +09:00
0fd63e85e7
fmsg/errors: isolate app/error into a separate package
These functions are not in any way specific to the app package.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-16 01:29:44 +09:00
33cf0bed54
dbus: various accessors for dbus.Proxy internal fields
These values are useful during sandbox setup and exporting them makes more sense than storing them twice.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-16 01:27:49 +09:00
689f5bed57
release: 0.0.4
All checks were successful
release / release (push) Successful in 1m32s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-15 02:56:49 +09:00
184a5f29fa
helper/bwrap: add fortify permissive default test case
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-15 02:56:13 +09:00
3015266e5a
helper/bwrap: sort SetEnv arguments
This guarantees consistency of resulting args.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-15 02:55:48 +09:00
aa5dd2313c
app: filter /tmp from permissive default
Tmpdir is bind mounted over further along in execution so there is no point sharing it here.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-15 02:54:50 +09:00
2faf510146
helper/bwrap: ordered filesystem args
The argument builder was written based on the incorrect assumption that bwrap arguments are unordered. The argument builder is replaced in this commit to correct that mistake.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-15 02:15:55 +09:00
a0db19b9ad
helper/bwrap: format mode in octal
Bubblewrap expects an octal representation of mode.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-14 13:47:50 +09:00
aaed5080f4
fortify: move PR_SET_DUMPABLE to the beginning of main
This call does need flag values.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-14 02:48:37 +09:00
41a7eb567e
release: 0.0.3
All checks were successful
release / release (push) Successful in 2m38s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-14 02:31:11 +09:00
1302bcede0
init: custom init process inside sandbox
Bubblewrap as init is a bit awkward and don't support a few setup actions fortify will need, such as starting/supervising nscd.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-14 02:27:02 +09:00
315c9b8849
fortify: refuse to run as root
There is no good reason to run fortify as root and desktop environments typically do not like that either. This check prevents confusion for new users who might mistakenly run it as root or set the setuid bit.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 20:06:47 +09:00
3739b56504
shim: update payload comment
Generating permissive default no longer happens in shim.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 17:19:50 +09:00
77f2c320a6
shim: re-exec self on startup
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 16:56:10 +09:00
b470941911
shim: get rid of insane launch condition
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 12:09:38 +09:00
e4536b87ad
app: generate and replace passwd and group files
This ensures libc functions get correct user information.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 02:43:00 +09:00
65a5f8fb08
app/config: map bwrap tmpfs in app config
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 02:39:27 +09:00
aee96b0fdf
helper/bwrap: allow pushing generic arguments to the end of argument stream
Bwrap argument order determines the order their corresponding actions are performed. This allows generic arguments like tmpfs to the end of the stream to override bind mounts.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 02:26:01 +09:00
655020eb5d
app/config: always use nobody UID within sandbox
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 00:50:24 +09:00
f320dfc2ee
fortify: set SUID_DUMP_DISABLE after flag parse
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 00:09:14 +09:00
c818ea649a
app/seal: skip /mnt in permissive default
This directory usually contains temporarily mounted stuff and shouldn't get into the sandbox.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 00:07:48 +09:00
b091260fd3
update README document
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-13 00:07:10 +09:00
b9d5fe49cb
nix: pass $SHELL for shell interpreter
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 23:01:06 +09:00
d37dcff2fc
app/seal: allow GPU access in permissive default when either X11/Wayland is enabled
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 22:55:53 +09:00
805ef99f9b
app: filesystem struct that maps to all bwrap bind options
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 22:33:04 +09:00
283bcba05b
fortify/config: flag to print template config serialised as JSON
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 19:46:40 +09:00
2e019e48c1
app: supply template config
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 19:46:07 +09:00
d5c26ae593
fortify: move error handling to separate file
Error handling here is way too monstrous due to terrible design of the internal/app package. Since rewriting internal/app will take a while, error handling is moved out of main to improve readability.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 02:11:43 +09:00
61b473a06f
fortify: clean up config loading
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 01:51:06 +09:00
d2575b6708
fortify: move flag handling to separate files
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 01:28:22 +09:00
8d82446d97
helper: remove unused bwrap config field
This configuration is not saved anywhere, and does not need to be saved. Bwrap configuration information is already saved into p.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 00:55:14 +09:00
0f421644be
dbus: improve unsealed behaviour coverage
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-12 00:53:08 +09:00
662f2a9d2c
app: integrate bwrap into environment setup
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 04:18:15 +09:00
3ddfd76cdf
shim: use bwrap config as it is
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 04:13:56 +09:00
713872a5cd
helper/bwrap: move interfaceArgs before stringArgs
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 04:12:47 +09:00
6220f7e197
app: migrate to new shim implementation
Both machinectl and sudo launch methods launch shim as shim is now responsible for setting up the sandbox. Various app structures are adapted to accommodate bwrap configuration and mediated wayland access.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 02:01:03 +09:00
b86fa6b4c9
shim: new shim implementation
This implementation of shim accepts configuration as a gob stream over a unix socket, with support for mediating access to wayland via WAYLAND_SOCKET fd. All configuration is now included in the payload, and child is started inside bwrap configured with supplied bwrap.Config.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 01:55:33 +09:00
6eb712aec7
verbose: overridable prefix
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 01:49:11 +09:00
101e49a48b
helper/bwrap: proc, dev and mqueue as string arguments
These flags do not support --chmod.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-11 01:30:11 +09:00
a3aadd4146
app: tag ACL operations for revert
ACL operations are now tagged with the enablement causing them. At the end of child process's life, enablements of all remaining launchers are resolved and inverted. This allows Wait to only revert operations targeting resources no longer required by other launchers.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-10 14:33:58 +09:00
86cb5ac1db
app: hardlink sockets to process-specific share local to XDG_RUNTIME_DIR
This avoids adding ACLs to the PulseAudio directory.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-10 12:44:08 +09:00
2220055e26
state/simple: prefix store path
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-10 11:03:31 +09:00
f4c44a9441
release: 0.0.2
All checks were successful
release / release (push) Successful in 2m15s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-10 00:13:06 +09:00
8f03ddc3fa
app: remove bubblewrap launch method
Launch methods serve the primary purpose of setting UID in the init namespace, which bubblewrap does not do. Furthermore, all applications will start within a bubblewrap sandbox once it has been implemented.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-10 00:11:04 +09:00
d41b9d2d9c
ldd: separate Parse from Exec and trim space
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 23:51:15 +09:00
22dfa73efe
release: 0.0.1
All checks were successful
release / release (push) Successful in 1m51s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 20:48:38 +09:00
753c5191b1
dbus/run: support running xdg-dbus-proxy in a restrictive bubblewrap sandbox
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 20:41:42 +09:00
6232291cae
ldd: implement strict ldd output parser
Fortify needs to internally resolve helper program sandbox config. They are considered trusted and runs under the privileged UID so ldd output is used to determine libraries they need inside the sandbox environment.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 20:39:27 +09:00
b99ed94386
helper/bwrap: pass --unshare-user when unshare everything
Bubblewrap apparently requires --unshare-user even when --unshare-all is set to apply --disable-userns. This behaviour is not clearly documented.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 00:22:48 +09:00
c201c30c7f
helper/bwrap: check args only for internal tests
Tests internal to the helper package sets crash-test-dummy as the command whenever a launch is expected to go through, and the hardcoded args are only valid for internal tests, so this characteristic is used here to exclude external tests that pass real program names and custom bwrap configurations.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-09 00:21:31 +09:00
7c7999e9e5
helper: implementation of helper.Helper using bwrap
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-08 18:02:38 +09:00
c6223771db
helper: generalise helper.Helper test
For testing the upcoming bwrap implementation of helper.Helper as it must have identical behaviour.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-08 14:02:54 +09:00
3c5185d770
helper: move test sample data out of direct
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 22:51:08 +09:00
55a5b6f242
dbus: use name resolved by exec.Command
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 16:55:27 +09:00
85407dd3c0
helper: helper.Helper interface
For upcoming bwrap implementation of helper.Helper

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 15:37:52 +09:00
6a2802cf30
helper: move bwrap into helper
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 14:40:35 +09:00
0fb9e40191
helper/args: MustNewCheckedArgs for cleaner hardcoded args
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 13:33:18 +09:00
9647eb6a6b
helper: separate pipes from Helper
Upcoming bwrap helper implementation requires two sets of pipes to be managed, fd will also no longer be constant.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-07 12:48:20 +09:00
18d9ce733e
helper: test non-existent helpers
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-10-06 16:00:59 +09:00
ba76e2919b
bwrap: implement argument builder
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-30 00:25:15 +09:00
df29068d16
verbose: test verbose behaviour
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 16:36:59 +09:00
d1415305ae
dbus: test child process handling behaviour via helper stub
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 15:49:32 +09:00
98f9fdb7cc
dbus: configurable xdg-dbus-proxy output
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 15:27:29 +09:00
dc59f20d7b
dbus: toggleable xdg-dbus-proxy output
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 15:24:54 +09:00
7e7327ebf8
helper: export internal stub functions for cross-package testing
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 15:22:35 +09:00
3bf456da65
helper: test child process handling
The stub child process simulates reading from the argument fd and copies the entire payload unmodified to stdout. If status pipe is enabled it will simulate sync fd behaviour as well.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 14:59:39 +09:00
61ba841c88
helper: remove unreachable check
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 14:48:38 +09:00
d530a9e9f9
helper: stub helper for tests
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-29 14:40:01 +09:00
0e7849fac2
dbus: add more test cases
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-28 19:19:31 +09:00
342c66aae8
dbus: replace test suffix * with +
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-28 17:47:15 +09:00
cf182d1fbe
dbus: seal test error check for correct error returned
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-28 17:00:20 +09:00
996bf67ac2
release: 0.0.0-beta.5
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-28 00:25:16 +09:00
1038af98f0
dbus: add tests
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-28 00:06:16 +09:00
aa2be18f47
dbus/config: implement file loading functions
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-27 23:53:08 +09:00
84d8c27b5f
dbus: return exported error for nil config
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-27 23:52:38 +09:00
ee2f5ed6ac
dbus/config: remove unused method
Null checking is replaced by helper/args while string building is no longer required.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-27 12:04:28 +09:00
8492239cba
helper/args: simplify argument parsing and eliminate excess memory copies
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-25 14:00:30 +09:00
a8b4b3634b
dbus: use generalised helper.Helper for xdg-dbus-proxy
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-25 01:17:38 +09:00
97bab6c406
helper: clean up and separate helper process management from dbus
The previous code was poorly documented and made little sense in some parts. This is a generalised and cleaned up implementation in the helper package making use of the Args interface.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-25 01:16:06 +09:00
831b1aad6f
helper/args: hold a read lock in WriteTo
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-24 20:22:37 +09:00
be83ad838c
dbus: assert fmt.Stringer instead of helper.Args on argument seal
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-24 19:37:50 +09:00
b722adc4dd
dbus: seal as io.WriterTo interface
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-24 18:03:05 +09:00
000607da5f
helper: separate helper args fd builder from dbus
This method of passing arguments is used in bubblewrap as well as other tools, this commit separates the argument builder/writer to the helper package and generalise it as an interface.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-24 16:11:08 +09:00
1cb90c0840
app: improve dbus proxy verbose messages
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-24 13:44:42 +09:00
a75229991c
nix: make bubblewrap available in PATH
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-23 18:21:12 +09:00
ced31a7257
state: round printed uptime to the second
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-22 16:15:21 +09:00
61628dabb7
nix: remove obnoxious shell hook
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-22 16:08:11 +09:00
9a9fcdb9ec
release: 0.0.0-beta.4
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-22 01:18:47 +09:00
62cb8a91b6
app: clean up interactions and handle all application state and setup/teardown
There was an earlier attempt of cleaning up the app package however it ended up creating even more of a mess and the code structure largely still looked like Ego with state setup scattered everywhere and a bunch of ugly hacks had to be implemented to keep track of all of them. In this commit the entire app package is rewritten to track everything that has to do with an app in one thread safe value.

In anticipation of the client/server split also made changes:
- Console messages are cleaned up to be consistent
- State tracking is fully rewritten to be cleaner and usable for multiple process and client/server
- Encapsulate errors to easier identify type of action causing the error as well as additional info
- System-level setup operations is grouped in a way that can be collectively committed/reverted
  and gracefully handles errors returned by each operation
- Resource sharing is made more fine-grained with PID-scoped resources whenever possible,
  a few remnants (X11, Wayland, PulseAudio) will be addressed when a generic proxy is available
- Application setup takes a JSON-friendly config struct and deterministically generates system setup operations

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-22 01:15:39 +09:00
11832a9379
acl: define Go type alias for acl_perm_t
Define exported type alias for C.acl_perm_t and accept that for UpdatePerm. This makes representing its function signature significantly less cumbersome.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-21 22:25:03 +09:00
2763ec730e
release: 0.0.0-beta.3
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-17 23:17:39 +09:00
3d963b9f67
nix: include package buildInputs in devShells
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-17 23:15:33 +09:00
4b7d616862
exit: move final and early code to internal package
Exit cleanup state information is now stored in a dedicated struct and built up using methods of that struct.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-17 13:48:42 +09:00
6a6f62efa6
release: 0.0.0-beta.2
This project started as a Go implementation of https://github.com/intgr/ego. That is clearly no longer what it is anymore and the tagged releases no longer made sense, so we're going back to v0.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-16 20:41:02 +09:00
03c24c5122
move acl and xcb binding packages to top level
These packages are reasonably clean and do not interact with other packages.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-16 20:32:07 +09:00
8bdae74ebe
final: refactor for removal of system package and reduction of interactions to state package
State query command has been moved to main where it belongs, "system" information are now fetched in app.New and stored in *App with accessors for relevant values. Exit (cleanup-related) functions are separated into its dedicated "final" package.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-16 20:31:35 +09:00
d49b97b1d4
nix: pass method string directly
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-13 11:58:45 +09:00
40d0550ad3
flag: move method flag from main
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-13 11:49:10 +09:00
da6d238d8a
verbose: remove system package interaction
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-12 21:07:05 +09:00
b0aff89166
app: handle launch method in New function
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-12 20:53:33 +09:00
8223a9ee66
enable filter in README example
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-11 16:35:23 +09:00
88ac05be6d
nix: fix typo in nixos module implementation previously missed due to lazy eval
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 23:29:16 +09:00
0ef321ad6f
update README document
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 23:22:07 +09:00
52f986559c
app/run: empty launcher environment
The launcher process should not receive the child's environment.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 22:24:58 +09:00
396066de7b
nix: implement dbus-system option in nixos module
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 21:26:14 +09:00
44301cd979
app/dbus: accept system bus config
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 21:19:12 +09:00
20c0e66d8f
dbus/config: seal with session and system bus proxy
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 21:13:00 +09:00
e5918ba3b3
dbus/config: fix builtin defaults
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 19:20:37 +09:00
35d040590b
dbus/config: document fields and add --call and --broadcast
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 13:27:31 +09:00
c1bfe2cd74
release: 1.1.0
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 05:14:53 +09:00
d813f8e44e
update README document
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 05:14:14 +09:00
0e5b85fd42
nix: implement new dbus options in nixos module
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 04:58:25 +09:00
cdc08817a7
nix: add xdg-dbus-proxy to PATH via wrapProgram
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 04:37:12 +09:00
e5b3fa02f9
flag: rename cli to flag
Yet another leftover from Ego. The cli name made no sense and this file only contains flag declarations now hence the rename.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 04:21:13 +09:00
8e848366cd
app/dbus: set dbusAddress early
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 03:46:46 +09:00
38ef2b4d0c
app/dbus: manage dbus proxy and pass address to child
This commit adds code that starts and registers the D-Bus proxy, as well as cleanup code that tracks and closes the daemon once our child exits. A few more flags were added to pass D-Bus config to xdg-dbus-proxy.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 03:16:54 +09:00
357cc4ce4d
dbus: implement xdg-dbus-proxy wrapper
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 03:11:50 +09:00
3242ce3406
app: treat display server variable unset as fatal
This is yet another remnant of Ego, as Ego unconditionally shares these resources and the absence of them are ignored and warned about in verbose logging. In our case they are individually opt-in so silently dropping them while the enablement is still set makes very little sense.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 00:35:16 +09:00
7450b0b0bb
app/run: remove bare launch option
This flag serves no use and is only a leftover from Ego.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-09 00:32:17 +09:00
83af555c97
state/print: collect and output state information of all users
The -state flag now outputs state of all users. The old behaviour can be accessed via the -state-current flag, user is selected via -u.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-08 13:19:48 +09:00
60e4846542
nix: provide options for capability flags
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-08 02:45:00 +09:00
1906853382
clean up setup/launcher code and enable better control over shares
In the past Wayland, X and PulseAudio are shared unconditionally. This can unnecessarily increase attack surface as some of these resources might not be needed at all. This commit moves all environment preparation code to the internal app package and selectively call them based on flags.

An "enablements" bitfield is introduced tracking all enabled shares. This value is registered after successful child process launch and stored in launcher states.

Code responsible for running the child process is isolated to its own app/run file and cleaned up. Launch method selection is also extensively cleaned up.

The internal state/track readLaunchers function now takes uid as an argument. Launcher state is now printed using text/tabwriter and argv is only emitted when verbose.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-08 02:24:01 +09:00
58d3a1fbc7
release: 1.0.4
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 19:57:47 +09:00
1b5fce5ccb
update README document
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 19:54:35 +09:00
945cce2f5e
nix: implement nixos module
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 17:03:21 +09:00
5c3e7cf664
app/launch: set argv when launching shell
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 11:04:16 +09:00
743b6afbbb
workflows: rename binary to fortify
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 01:27:04 +09:00
d8f76f3b25
rename to fortify and restructure
More sandbox features will be added and this will no longer track ego's features and behaviour.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-09-04 01:20:12 +09:00
129 changed files with 12079 additions and 1110 deletions

46
.gitea/workflows/nix.yml Normal file
View File

@ -0,0 +1,46 @@
name: Nix
on:
- push
- pull_request
jobs:
tests:
name: NixOS tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Install Nix
uses: cachix/install-nix-action@08dcb3a5e62fa31e2da3d490afc4176ef55ecd72 # v30
with:
# explicitly enable sandbox
install_options: --daemon
extra_nix_config: |
sandbox = true
system-features = nixos-test benchmark big-parallel kvm
enable_kvm: true
- name: Ensure environment
run: >-
apt-get update && apt-get install -y sqlite3
if: ${{ runner.os == 'Linux' }}
- name: Restore Nix store
uses: nix-community/cache-nix-action@v5
with:
primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix') }}
restore-prefixes-first-match: nix-${{ runner.os }}-
- name: Run tests
run: |
nix --print-build-logs --experimental-features 'nix-command flakes' flake check --all-systems
nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.nixos-tests
- name: Upload test output
uses: actions/upload-artifact@v3
with:
name: "result"
path: result/*
retention-days: 1

View File

@ -1,4 +1,4 @@
name: release name: Create distribution
on: on:
push: push:
@ -7,32 +7,47 @@ on:
jobs: jobs:
release: release:
name: Release
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: node:16-bookworm-slim
steps: steps:
- name: Get dependencies
run: >-
echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list &&
apt-get update &&
apt-get install -y
acl
git
gcc
pkg-config
libwayland-dev
wayland-protocols/bookworm-backports
libxcb1-dev
libacl1-dev
if: ${{ runner.os == 'Linux' }}
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up go
- name: Setup go
uses: https://github.com/actions/setup-go@v5 uses: https://github.com/actions/setup-go@v5
with: with:
go-version: '>=1.20.1' go-version: '>=1.23.0'
- name: Get dependencies
- name: Go generate
run: >- run: >-
sudo apt-get update && go generate ./...
sudo apt-get install -y
gcc - name: Build for release
pkg-config run: FORTIFY_VERSION='${{ github.ref_name }}' ./dist/release.sh
libacl1-dev
if: ${{ runner.os == 'Linux' }}
- name: Build for Linux
run: >-
sh -c "go build -v -ldflags '-s -w -X main.Version=${{ github.ref_name }}' -o bin/ego &&
sha256sum --tag -b bin/ego > bin/ego.sha256"
- name: Release - name: Release
id: use-go-action id: use-go-action
uses: https://gitea.com/actions/release-action@main uses: https://gitea.com/actions/release-action@main
with: with:
files: |- files: |-
bin/** dist/fortify-**
api_key: '${{secrets.RELEASE_TOKEN}}' api_key: '${{secrets.RELEASE_TOKEN}}'

62
.gitea/workflows/test.yml Normal file
View File

@ -0,0 +1,62 @@
name: Tests
on:
- push
- pull_request
jobs:
test:
name: Go tests
runs-on: ubuntu-latest
container:
image: node:16-bookworm-slim
steps:
- name: Enable backports
run: >-
echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list
if: ${{ runner.os == 'Linux' }}
- name: Ensure environment
run: >-
apt-get update && apt-get install -y curl wget sudo libxml2
if: ${{ runner.os == 'Linux' }}
- name: Get dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: acl git gcc pkg-config libwayland-dev wayland-protocols/bookworm-backports libxcb1-dev libacl1-dev
version: 1.0
#execute_install_scripts: true
if: ${{ runner.os == 'Linux' }}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup go
uses: https://github.com/actions/setup-go@v5
with:
go-version: '>=1.23.0'
- name: Go generate
run: >-
go generate ./...
- name: Run tests
run: >-
go test ./...
- name: Build for test
id: build-test
run: >-
FORTIFY_VERSION="$(git rev-parse --short HEAD)"
bash -c './dist/release.sh &&
echo "rev=$FORTIFY_VERSION" >> $GITHUB_OUTPUT'
- name: Upload test build
uses: actions/upload-artifact@v3
with:
name: "fortify-${{ steps.build-test.outputs.rev }}"
path: dist/fortify-*
retention-days: 1

8
.gitignore vendored
View File

@ -4,7 +4,7 @@
*.dll *.dll
*.so *.so
*.dylib *.dylib
/ego /fortify
# Test binary, built with `go test -c` # Test binary, built with `go test -c`
*.test *.test
@ -23,3 +23,9 @@ go.work.sum
.env .env
.idea .idea
.vscode .vscode
# go generate
security-context-v1-protocol.*
# release
/dist/fortify-*

221
README.md
View File

@ -1,83 +1,162 @@
ego (the Go side) Fortify
================= =======
[![Go Reference](https://pkg.go.dev/badge/git.ophivana.moe/cat/ego.svg)](https://pkg.go.dev/git.ophivana.moe/cat/ego) [![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)
> Do all your games need access to your documents, browser history, SSH private keys? 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.
> ... No? Just run `ego steam`!
**Ego** is a tool to run Linux desktop applications under a different local user. Currently Why would you want this?
integrates with Wayland, Xorg, PulseAudio and xdg-desktop-portal. You may think of it as `xhost`
for Wayland and PulseAudio. This is done using filesystem ACLs and X11 host access control.
Disclaimer: **DO NOT RUN UNTRUSTED PROGRAMS VIA EGO.** However, using ego is more secure than - It protects the desktop environment from applications.
running applications directly under your primary user.
Differences - It protects applications from each other.
-----------
* Written in Go
* Tracks process states
* Cleans up after last process exits
* Argv preservation in machinectl mode
* Has no dependencies other than the two C libraries
Manual setup - It provides UID isolation on top of the standard application sandbox.
------------
Ego aims to come with sane defaults and be easy to set up.
**Requirements:** If you have a flakes-enabled nix environment, you can try out the tool by running:
* Sudo
* A C compiler
* [Go](https://go.dev/doc/install)
* `libacl.so` library (Debian/Ubuntu: libacl1-dev; Fedora: libacl-devel; Arch: acl)
* `libxcb.so` library (Debian/Ubuntu: libxcb1-dev; Fedora: libxcb-devel; Arch: libxcb)
**Recommended:** (Not needed when using `--sudo` mode, but some desktop functionality may not work). ```shell
* `machinectl` command (Debian/Ubuntu/Fedora: systemd-container; Arch: systemd) nix run git+https://git.gensokyo.uk/security/fortify -- help
* `xdg-desktop-portal-gtk` (Debian/Ubuntu/Fedora/Arch: xdg-desktop-portal-gtk)
**Installation:**
1. Run in repository worktree:
go build -v -ldflags '-s -w'
sudo cp ego /usr/local/bin/
2. Create local user named "ego": <sup>[1]</sup>
sudo useradd ego --uid 155 --create-home
3. That's all, try it:
ego xdg-open .
[1] No extra groups are needed by the ego user.
UID below 1000 hides this user on the login screen.
### Avoid password prompt
If using "machinectl" mode (default if available), you need the rather new systemd version >=247
and polkit >=0.106 to do this securely.
Create file `/etc/polkit-1/rules.d/50-ego-machinectl.rules`, polkit will automatically load it
(replace `$USER` with your own username):
```js
polkit.addRule(function(action, subject) {
if (action.id == "org.freedesktop.machine1.host-shell" &&
action.lookup("user") == "ego" &&
subject.user == "$USER") {
return polkit.Result.YES;
}
});
``` ```
##### sudo mode ## Module usage
For sudo, add the following to `/etc/sudoers` (replace `$USER` with your own username):
$USER ALL=(ego) NOPASSWD:ALL The NixOS module currently requires home-manager to function correctly.
Appendix Full module documentation can be found [here](options.md).
--------
Ego is licensed under the MIT License (see the `LICENSE` file). To use the module, import it into your configuration with
The original Ego was created by Marti Raudsepp under the repository https://github.com/intgr/ego
```nix
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
fortify = {
url = "git+https://git.gensokyo.uk/security/fortify";
# Optional but recommended to limit the size of your system closure.
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, fortify, ... }:
{
nixosConfigurations.fortify = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
fortify.nixosModules.fortify
];
};
};
}
```
This adds the `environment.fortify` option:
```nix
{ pkgs, ... }:
{
environment.fortify = {
enable = true;
stateDir = "/var/lib/persist/module/fortify";
users = {
alice = 0;
nixos = 10;
};
apps = [
{
name = "chromium";
id = "org.chromium.Chromium";
packages = [ pkgs.chromium ];
userns = true;
mapRealUid = true;
dbus = {
system = {
filter = true;
talk = [
"org.bluez"
"org.freedesktop.Avahi"
"org.freedesktop.UPower"
];
};
session =
f:
f {
talk = [
"org.freedesktop.FileManager1"
"org.freedesktop.Notifications"
"org.freedesktop.ScreenSaver"
"org.freedesktop.secrets"
"org.kde.kwalletd5"
"org.kde.kwalletd6"
];
own = [
"org.chromium.Chromium.*"
"org.mpris.MediaPlayer2.org.chromium.Chromium.*"
"org.mpris.MediaPlayer2.chromium.*"
];
call = { };
broadcast = { };
};
};
}
{
name = "claws-mail";
id = "org.claws_mail.Claws-Mail";
packages = [ pkgs.claws-mail ];
gpu = false;
capability.pulse = false;
}
{
name = "weechat";
packages = [ pkgs.weechat ];
capability = {
wayland = false;
x11 = false;
dbus = true;
pulse = false;
};
}
{
name = "discord";
id = "dev.vencord.Vesktop";
packages = [ pkgs.vesktop ];
share = pkgs.vesktop;
command = "vesktop --ozone-platform-hint=wayland";
userns = true;
mapRealUid = true;
capability.x11 = true;
dbus = {
session =
f:
f {
talk = [ "org.kde.StatusNotifierWatcher" ];
own = [ ];
call = { };
broadcast = { };
};
system.filter = true;
};
}
{
name = "looking-glass-client";
groups = [ "plugdev" ];
extraPaths = [
{
src = "/dev/shm/looking-glass";
write = true;
}
];
extraConfig = {
programs.looking-glass-client.enable = true;
};
}
];
};
}
```

176
acl.go
View File

@ -1,176 +0,0 @@
package main
import (
"errors"
"fmt"
"syscall"
"unsafe"
)
//#include <stdlib.h>
//#include <sys/acl.h>
//#include <acl/libacl.h>
//#cgo linux LDFLAGS: -lacl
import "C"
const (
aclRead = C.ACL_READ
aclWrite = C.ACL_WRITE
aclExecute = C.ACL_EXECUTE
aclTypeDefault = C.ACL_TYPE_DEFAULT
aclTypeAccess = C.ACL_TYPE_ACCESS
aclUndefinedTag = C.ACL_UNDEFINED_TAG
aclUserObj = C.ACL_USER_OBJ
aclUser = C.ACL_USER
aclGroupObj = C.ACL_GROUP_OBJ
aclGroup = C.ACL_GROUP
aclMask = C.ACL_MASK
aclOther = C.ACL_OTHER
)
type acl struct {
val C.acl_t
freed bool
}
func aclUpdatePerm(path string, uid int, perms ...C.acl_perm_t) error {
// read acl from file
a, err := aclGetFile(path, aclTypeAccess)
if err != nil {
return err
}
// free acl on return if get is successful
defer a.free()
// remove existing entry
if err = a.removeEntry(aclUser, uid); err != nil {
return err
}
// create new entry if perms are passed
if len(perms) > 0 {
// create new acl entry
var e C.acl_entry_t
if _, err = C.acl_create_entry(&a.val, &e); err != nil {
return err
}
// get perm set of new entry
var p C.acl_permset_t
if _, err = C.acl_get_permset(e, &p); err != nil {
return err
}
// add target perms
for _, perm := range perms {
if _, err = C.acl_add_perm(p, perm); err != nil {
return err
}
}
// set perm set to new entry
if _, err = C.acl_set_permset(e, p); err != nil {
return err
}
// set user tag to new entry
if _, err = C.acl_set_tag_type(e, aclUser); err != nil {
return err
}
// set qualifier (uid) to new entry
if _, err = C.acl_set_qualifier(e, unsafe.Pointer(&uid)); err != nil {
return err
}
}
// calculate mask after update
if _, err = C.acl_calc_mask(&a.val); err != nil {
return err
}
// write acl to file
return a.setFile(path, aclTypeAccess)
}
func aclGetFile(path string, t C.acl_type_t) (*acl, error) {
p := C.CString(path)
a, err := C.acl_get_file(p, t)
C.free(unsafe.Pointer(p))
if errors.Is(err, syscall.ENODATA) {
err = nil
}
return &acl{val: a, freed: false}, err
}
func (a *acl) setFile(path string, t C.acl_type_t) error {
if C.acl_valid(a.val) != 0 {
return fmt.Errorf("invalid acl")
}
p := C.CString(path)
_, err := C.acl_set_file(p, t, a.val)
C.free(unsafe.Pointer(p))
return err
}
func (a *acl) removeEntry(tt C.acl_tag_t, tq int) error {
var e C.acl_entry_t
// get first entry
if r, err := C.acl_get_entry(a.val, C.ACL_FIRST_ENTRY, &e); err != nil {
return err
} else if r == 0 {
// return on acl with no entries
return nil
}
for {
if r, err := C.acl_get_entry(a.val, C.ACL_NEXT_ENTRY, &e); err != nil {
return err
} else if r == 0 {
// return on drained acl
return nil
}
var (
q int
t C.acl_tag_t
)
// get current entry tag type
if _, err := C.acl_get_tag_type(e, &t); err != nil {
return err
}
// get current entry qualifier
if rq, err := C.acl_get_qualifier(e); err != nil {
// neither ACL_USER nor ACL_GROUP
if errors.Is(err, syscall.EINVAL) {
continue
}
return err
} else {
q = *(*int)(rq)
C.acl_free(rq)
}
// delete on match
if t == tt && q == tq {
_, err := C.acl_delete_entry(a.val, e)
return err
}
}
}
func (a *acl) free() {
if a.freed {
panic("acl already freed")
}
C.acl_free(unsafe.Pointer(a.val))
a.freed = true
}

19
acl/acl.go Normal file
View File

@ -0,0 +1,19 @@
// Package acl implements simple ACL manipulation via libacl.
package acl
type Perms []Perm
func (ps Perms) String() string {
var s = []byte("---")
for _, p := range ps {
switch p {
case Read:
s[0] = 'r'
case Write:
s[1] = 'w'
case Execute:
s[2] = 'x'
}
}
return string(s)
}

156
acl/acl_getfacl_test.go Normal file
View File

@ -0,0 +1,156 @@
package acl_test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os/exec"
"strconv"
)
type (
getFAclInvocation struct {
cmd *exec.Cmd
val []*getFAclResp
pe []error
}
getFAclResp struct {
typ fAclType
cred int32
val fAclPerm
raw []byte
}
fAclPerm uintptr
fAclType uint8
)
const fAclBufSize = 16
const (
fAclPermRead fAclPerm = 1 << iota
fAclPermWrite
fAclPermExecute
)
const (
fAclTypeUser fAclType = iota
fAclTypeGroup
fAclTypeMask
fAclTypeOther
)
func (c *getFAclInvocation) run(name string) error {
if c.cmd != nil {
panic("attempted to run twice")
}
c.cmd = exec.Command("getfacl", "--omit-header", "--absolute-names", "--numeric", name)
scanErr := make(chan error, 1)
if p, err := c.cmd.StdoutPipe(); err != nil {
return err
} else {
go c.parse(p, scanErr)
}
if err := c.cmd.Start(); err != nil {
return err
}
return errors.Join(<-scanErr, c.cmd.Wait())
}
func (c *getFAclInvocation) parse(pipe io.Reader, scanErr chan error) {
c.val = make([]*getFAclResp, 0, 4+fAclBufSize)
s := bufio.NewScanner(pipe)
for s.Scan() {
fields := bytes.SplitN(s.Bytes(), []byte{':'}, 3)
if len(fields) != 3 {
continue
}
resp := getFAclResp{}
switch string(fields[0]) {
case "user":
resp.typ = fAclTypeUser
case "group":
resp.typ = fAclTypeGroup
case "mask":
resp.typ = fAclTypeMask
case "other":
resp.typ = fAclTypeOther
default:
c.pe = append(c.pe, fmt.Errorf("unknown type %s", string(fields[0])))
continue
}
if len(fields[1]) == 0 {
resp.cred = -1
} else {
if cred, err := strconv.Atoi(string(fields[1])); err != nil {
c.pe = append(c.pe, err)
continue
} else {
resp.cred = int32(cred)
if resp.cred < 0 {
c.pe = append(c.pe, fmt.Errorf("credential %d out of range", resp.cred))
continue
}
}
}
if len(fields[2]) != 3 {
c.pe = append(c.pe, fmt.Errorf("invalid perm length %d", len(fields[2])))
continue
} else {
switch fields[2][0] {
case 'r':
resp.val |= fAclPermRead
case '-':
default:
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][0]))
continue
}
switch fields[2][1] {
case 'w':
resp.val |= fAclPermWrite
case '-':
default:
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][1]))
continue
}
switch fields[2][2] {
case 'x':
resp.val |= fAclPermExecute
case '-':
default:
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][2]))
continue
}
}
resp.raw = make([]byte, len(s.Bytes()))
copy(resp.raw, s.Bytes())
c.val = append(c.val, &resp)
}
scanErr <- s.Err()
}
func (r *getFAclResp) String() string {
if r.raw != nil && len(r.raw) > 0 {
return string(r.raw)
}
return "(user-initialised resp value)"
}
func (r *getFAclResp) equals(typ fAclType, cred int32, val fAclPerm) bool {
return r.typ == typ && r.cred == cred && r.val == val
}

125
acl/acl_test.go Normal file
View File

@ -0,0 +1,125 @@
package acl_test
import (
"errors"
"os"
"path"
"reflect"
"testing"
"git.gensokyo.uk/security/fortify/acl"
)
const testFileName = "acl.test"
var (
uid = os.Geteuid()
cred = int32(os.Geteuid())
)
func TestUpdatePerm(t *testing.T) {
if os.Getenv("GO_TEST_SKIP_ACL") == "1" {
t.Log("acl test skipped")
t.SkipNow()
}
testFilePath := path.Join(t.TempDir(), testFileName)
if f, err := os.Create(testFilePath); err != nil {
t.Fatalf("Create: error = %v", err)
} else {
if err = f.Close(); err != nil {
t.Fatalf("Close: error = %v", err)
}
}
defer func() {
if err := os.Remove(testFilePath); err != nil {
t.Fatalf("Remove: error = %v", err)
}
}()
cur := getfacl(t, testFilePath)
t.Run("default entry count", func(t *testing.T) {
if len(cur) != 3 {
t.Fatalf("unexpected test file acl length %d", len(cur))
}
})
t.Run("default clear mask", func(t *testing.T) {
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
t.Fatalf("UpdatePerm: error = %v", err)
}
if cur = getfacl(t, testFilePath); len(cur) != 4 {
t.Fatalf("UpdatePerm: %v", cur)
}
})
t.Run("default clear consistency", func(t *testing.T) {
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
t.Fatalf("UpdatePerm: error = %v", err)
}
if val := getfacl(t, testFilePath); !reflect.DeepEqual(val, cur) {
t.Fatalf("UpdatePerm: %v, want %v", val, cur)
}
})
testUpdate(t, testFilePath, "r--", cur, fAclPermRead, acl.Read)
testUpdate(t, testFilePath, "-w-", cur, fAclPermWrite, acl.Write)
testUpdate(t, testFilePath, "--x", cur, fAclPermExecute, acl.Execute)
testUpdate(t, testFilePath, "-wx", cur, fAclPermWrite|fAclPermExecute, acl.Write, acl.Execute)
testUpdate(t, testFilePath, "r-x", cur, fAclPermRead|fAclPermExecute, acl.Read, acl.Execute)
testUpdate(t, testFilePath, "rw-", cur, fAclPermRead|fAclPermWrite, acl.Read, acl.Write)
testUpdate(t, testFilePath, "rwx", cur, fAclPermRead|fAclPermWrite|fAclPermExecute, acl.Read, acl.Write, acl.Execute)
}
func testUpdate(t *testing.T, testFilePath, name string, cur []*getFAclResp, val fAclPerm, perms ...acl.Perm) {
t.Run(name, func(t *testing.T) {
t.Cleanup(func() {
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
t.Fatalf("UpdatePerm: error = %v", err)
}
if v := getfacl(t, testFilePath); !reflect.DeepEqual(v, cur) {
t.Fatalf("UpdatePerm: %v, want %v", v, cur)
}
})
if err := acl.UpdatePerm(testFilePath, uid, perms...); err != nil {
t.Fatalf("UpdatePerm: error = %v", err)
}
r := respByCred(getfacl(t, testFilePath), fAclTypeUser, cred)
if r == nil {
t.Fatalf("UpdatePerm did not add an ACL entry")
}
if !r.equals(fAclTypeUser, cred, val) {
t.Fatalf("UpdatePerm(%s) = %s", name, r)
}
})
}
func getfacl(t *testing.T, name string) []*getFAclResp {
c := new(getFAclInvocation)
if err := c.run(name); err != nil {
t.Fatalf("getfacl: error = %v", err)
}
if len(c.pe) != 0 {
t.Errorf("errors encountered parsing getfacl output\n%s", errors.Join(c.pe...).Error())
}
return c.val
}
func respByCred(v []*getFAclResp, typ fAclType, cred int32) *getFAclResp {
j := -1
for i, r := range v {
if r.typ == typ && r.cred == cred {
if j != -1 {
panic("invalid acl")
}
j = i
}
}
if j == -1 {
return nil
}
return v[j]
}

196
acl/c.go Normal file
View File

@ -0,0 +1,196 @@
package acl
import "C"
import (
"errors"
"runtime"
"syscall"
"unsafe"
)
/*
#cgo linux pkg-config: libacl
#include <stdlib.h>
#include <sys/acl.h>
#include <acl/libacl.h>
static acl_t _go_acl_get_file(const char *path_p, acl_type_t type) {
acl_t acl = acl_get_file(path_p, type);
free((void *)path_p);
return acl;
}
static int _go_acl_set_file(const char *path_p, acl_type_t type, acl_t acl) {
if (acl_valid(acl) != 0) {
return -1;
}
int ret = acl_set_file(path_p, type, acl);
free((void *)path_p);
return ret;
}
*/
import "C"
func getFile(name string, t C.acl_type_t) (*ACL, error) {
a, err := C._go_acl_get_file(C.CString(name), t)
if errors.Is(err, syscall.ENODATA) {
err = nil
}
return newACL(a), err
}
func (acl *ACL) setFile(name string, t C.acl_type_t) error {
_, err := C._go_acl_set_file(C.CString(name), t, acl.acl)
return err
}
func newACL(a C.acl_t) *ACL {
acl := &ACL{a}
runtime.SetFinalizer(acl, (*ACL).free)
return acl
}
type ACL struct {
acl C.acl_t
}
func (acl *ACL) free() {
C.acl_free(unsafe.Pointer(acl.acl))
// no need for a finalizer anymore
runtime.SetFinalizer(acl, nil)
}
const (
Read = C.ACL_READ
Write = C.ACL_WRITE
Execute = C.ACL_EXECUTE
TypeDefault = C.ACL_TYPE_DEFAULT
TypeAccess = C.ACL_TYPE_ACCESS
UndefinedTag = C.ACL_UNDEFINED_TAG
UserObj = C.ACL_USER_OBJ
User = C.ACL_USER
GroupObj = C.ACL_GROUP_OBJ
Group = C.ACL_GROUP
Mask = C.ACL_MASK
Other = C.ACL_OTHER
)
type (
Perm C.acl_perm_t
)
func (acl *ACL) removeEntry(tt C.acl_tag_t, tq int) error {
var e C.acl_entry_t
// get first entry
if r, err := C.acl_get_entry(acl.acl, C.ACL_FIRST_ENTRY, &e); err != nil {
return err
} else if r == 0 {
// return on acl with no entries
return nil
}
for {
if r, err := C.acl_get_entry(acl.acl, C.ACL_NEXT_ENTRY, &e); err != nil {
return err
} else if r == 0 {
// return on drained acl
return nil
}
var (
q int
t C.acl_tag_t
)
// get current entry tag type
if _, err := C.acl_get_tag_type(e, &t); err != nil {
return err
}
// get current entry qualifier
if rq, err := C.acl_get_qualifier(e); err != nil {
// neither ACL_USER nor ACL_GROUP
if errors.Is(err, syscall.EINVAL) {
continue
}
return err
} else {
q = *(*int)(rq)
C.acl_free(rq)
}
// delete on match
if t == tt && q == tq {
_, err := C.acl_delete_entry(acl.acl, e)
return err
}
}
}
func UpdatePerm(name string, uid int, perms ...Perm) error {
// read acl from file
a, err := getFile(name, TypeAccess)
if err != nil {
return err
}
// free acl on return if get is successful
defer a.free()
// remove existing entry
if err = a.removeEntry(User, uid); err != nil {
return err
}
// create new entry if perms are passed
if len(perms) > 0 {
// create new acl entry
var e C.acl_entry_t
if _, err = C.acl_create_entry(&a.acl, &e); err != nil {
return err
}
// get perm set of new entry
var p C.acl_permset_t
if _, err = C.acl_get_permset(e, &p); err != nil {
return err
}
// add target perms
for _, perm := range perms {
if _, err = C.acl_add_perm(p, C.acl_perm_t(perm)); err != nil {
return err
}
}
// set perm set to new entry
if _, err = C.acl_set_permset(e, p); err != nil {
return err
}
// set user tag to new entry
if _, err = C.acl_set_tag_type(e, User); err != nil {
return err
}
// set qualifier (uid) to new entry
if _, err = C.acl_set_qualifier(e, unsafe.Pointer(&uid)); err != nil {
return err
}
}
// calculate mask after update
if _, err = C.acl_calc_mask(&a.acl); err != nil {
return err
}
// write acl to file
return a.setFile(name, TypeAccess)
}

50
cli.go
View File

@ -1,50 +0,0 @@
package main
import (
"errors"
"flag"
"fmt"
"os"
"os/user"
)
var (
userName string
methodFlags [2]bool
printVersion bool
mustPulse bool
)
func init() {
flag.StringVar(&userName, "u", "ego", "Specify a username")
flag.BoolVar(&methodFlags[0], "sudo", false, "Use 'sudo' to change user")
flag.BoolVar(&methodFlags[1], "bare", false, "Use 'machinectl' but skip xdg-desktop-portal setup")
flag.BoolVar(&mustPulse, "pulse", false, "Treat unavailable PulseAudio as fatal")
flag.BoolVar(&verbose, "v", false, "Verbose output")
flag.BoolVar(&printVersion, "V", false, "Print version")
}
func copyArgs() {
tryLauncher()
tryVersion()
tryLicense()
command = flag.Args()
if u, err := user.Lookup(userName); err != nil {
if errors.As(err, new(user.UnknownUserError)) {
fmt.Println("unknown user", userName)
} else {
// unreachable
panic(err)
}
os.Exit(1)
} else {
ego = u
}
if verbose {
fmt.Println("Running as user", ego.Username, "("+ego.Uid+"),", "command:", command)
}
}

13
cmd/finit/ipc/payload.go Normal file
View File

@ -0,0 +1,13 @@
package init0
const Env = "FORTIFY_INIT"
type Payload struct {
// target full exec path
Argv0 string
// child full argv
Argv []string
// verbosity pass through
Verbose bool
}

174
cmd/finit/main.go Normal file
View File

@ -0,0 +1,174 @@
package main
import (
"errors"
"os"
"os/exec"
"os/signal"
"path"
"syscall"
"time"
init0 "git.gensokyo.uk/security/fortify/cmd/finit/ipc"
"git.gensokyo.uk/security/fortify/internal"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/proc"
)
const (
// time to wait for linger processes after death of initial process
residualProcessTimeout = 5 * time.Second
)
// everything beyond this point runs within pid namespace
// proceed with caution!
func main() {
// sharing stdout with shim
// USE WITH CAUTION
fmsg.SetPrefix("init")
// setting this prevents ptrace
if err := internal.PR_SET_DUMPABLE__SUID_DUMP_DISABLE(); err != nil {
fmsg.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
panic("unreachable")
}
if os.Getpid() != 1 {
fmsg.Fatal("this process must run as pid 1")
panic("unreachable")
}
// re-exec
if len(os.Args) > 0 && (os.Args[0] != "finit" || len(os.Args) != 1) && path.IsAbs(os.Args[0]) {
if err := syscall.Exec(os.Args[0], []string{"finit"}, os.Environ()); err != nil {
fmsg.Println("cannot re-exec self:", err)
// continue anyway
}
}
// receive setup payload
var (
payload init0.Payload
closeSetup func() error
)
if f, err := proc.Receive(init0.Env, &payload); err != nil {
if errors.Is(err, proc.ErrInvalid) {
fmsg.Fatal("invalid config descriptor")
}
if errors.Is(err, proc.ErrNotSet) {
fmsg.Fatal("FORTIFY_INIT not set")
}
fmsg.Fatalf("cannot decode init setup payload: %v", err)
panic("unreachable")
} else {
fmsg.SetVerbose(payload.Verbose)
closeSetup = f
// child does not need to see this
if err = os.Unsetenv(init0.Env); err != nil {
fmsg.Printf("cannot unset %s: %v", init0.Env, err)
// not fatal
} else {
fmsg.VPrintln("received configuration")
}
}
// die with parent
if err := internal.PR_SET_PDEATHSIG__SIGKILL(); err != nil {
fmsg.Fatalf("prctl(PR_SET_PDEATHSIG, SIGKILL): %v", err)
}
cmd := exec.Command(payload.Argv0)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
cmd.Args = payload.Argv
cmd.Env = os.Environ()
if err := cmd.Start(); err != nil {
fmsg.Fatalf("cannot start %q: %v", payload.Argv0, err)
}
fmsg.Suspend()
// close setup pipe as setup is now complete
if err := closeSetup(); err != nil {
fmsg.Println("cannot close setup pipe:", err)
// not fatal
}
sig := make(chan os.Signal, 2)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
type winfo struct {
wpid int
wstatus syscall.WaitStatus
}
info := make(chan winfo, 1)
done := make(chan struct{})
go func() {
var (
err error
wpid = -2
wstatus syscall.WaitStatus
)
// keep going until no child process is left
for wpid != -1 {
if err != nil {
break
}
if wpid != -2 {
info <- winfo{wpid, wstatus}
}
err = syscall.EINTR
for errors.Is(err, syscall.EINTR) {
wpid, err = syscall.Wait4(-1, &wstatus, 0, nil)
}
}
if !errors.Is(err, syscall.ECHILD) {
fmsg.Println("unexpected wait4 response:", err)
}
close(done)
}()
// closed after residualProcessTimeout has elapsed after initial process death
timeout := make(chan struct{})
r := 2
for {
select {
case s := <-sig:
fmsg.VPrintln("received", s.String())
fmsg.Resume() // output could still be withheld at this point, so resume is called
fmsg.Exit(0)
case w := <-info:
if w.wpid == cmd.Process.Pid {
// initial process exited, output is most likely available again
fmsg.Resume()
switch {
case w.wstatus.Exited():
r = w.wstatus.ExitStatus()
case w.wstatus.Signaled():
r = 128 + int(w.wstatus.Signal())
default:
r = 255
}
go func() {
time.Sleep(residualProcessTimeout)
close(timeout)
}()
}
case <-done:
fmsg.Exit(r)
case <-timeout:
fmsg.Println("timeout exceeded waiting for lingering processes")
fmsg.Exit(r)
}
}
}

21
cmd/fshim/ipc/payload.go Normal file
View File

@ -0,0 +1,21 @@
package shim0
import (
"git.gensokyo.uk/security/fortify/helper/bwrap"
)
const Env = "FORTIFY_SHIM"
type Payload struct {
// child full argv
Argv []string
// bwrap, target full exec path
Exec [2]string
// bwrap config
Bwrap *bwrap.Config
// sync fd
Sync *uintptr
// verbosity pass through
Verbose bool
}

137
cmd/fshim/ipc/shim/shim.go Normal file
View File

@ -0,0 +1,137 @@
package shim
import (
"encoding/gob"
"errors"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
shim0 "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
"git.gensokyo.uk/security/fortify/internal"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/proc"
)
const shimSetupTimeout = 5 * time.Second
// used by the parent process
type Shim struct {
// user switcher process
cmd *exec.Cmd
// uid of shim target user
uid uint32
// string representation of application id
aid string
// string representation of supplementary group ids
supp []string
// fallback exit notifier with error returned killing the process
killFallback chan error
// shim setup payload
payload *shim0.Payload
}
func New(uid uint32, aid string, supp []string, payload *shim0.Payload) *Shim {
return &Shim{uid: uid, aid: aid, supp: supp, payload: payload}
}
func (s *Shim) String() string {
if s.cmd == nil {
return "(unused shim manager)"
}
return s.cmd.String()
}
func (s *Shim) Unwrap() *exec.Cmd {
return s.cmd
}
func (s *Shim) WaitFallback() chan error {
return s.killFallback
}
func (s *Shim) Start() (*time.Time, error) {
// start user switcher process and save time
var fsu string
if p, ok := internal.Check(internal.Fsu); !ok {
fmsg.Fatal("invalid fsu path, this copy of fshim is not compiled correctly")
panic("unreachable")
} else {
fsu = p
}
s.cmd = exec.Command(fsu)
var encoder *gob.Encoder
if fd, e, err := proc.Setup(&s.cmd.ExtraFiles); err != nil {
return nil, fmsg.WrapErrorSuffix(err,
"cannot create shim setup pipe:")
} else {
encoder = e
s.cmd.Env = []string{
shim0.Env + "=" + strconv.Itoa(fd),
"FORTIFY_APP_ID=" + s.aid,
}
}
if len(s.supp) > 0 {
fmsg.VPrintf("attaching supplementary group ids %s", s.supp)
s.cmd.Env = append(s.cmd.Env, "FORTIFY_GROUPS="+strings.Join(s.supp, " "))
}
s.cmd.Stdin, s.cmd.Stdout, s.cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
s.cmd.Dir = "/"
// pass sync fd if set
if s.payload.Bwrap.Sync() != nil {
fd := proc.ExtraFile(s.cmd, s.payload.Bwrap.Sync())
s.payload.Sync = &fd
}
fmsg.VPrintln("starting shim via fsu:", s.cmd)
fmsg.Suspend() // withhold messages to stderr
if err := s.cmd.Start(); err != nil {
return nil, fmsg.WrapErrorSuffix(err,
"cannot start fsu:")
}
startTime := time.Now().UTC()
// kill shim if something goes wrong and an error is returned
s.killFallback = make(chan error, 1)
killShim := func() {
if err := s.cmd.Process.Signal(os.Interrupt); err != nil {
s.killFallback <- err
}
}
defer func() { killShim() }()
// take alternative exit path on signal
sig := make(chan os.Signal, 2)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
v := <-sig
fmsg.Printf("got %s after program start", v)
s.killFallback <- nil
signal.Ignore(syscall.SIGINT, syscall.SIGTERM)
}()
shimErr := make(chan error)
go func() { shimErr <- encoder.Encode(s.payload) }()
select {
case err := <-shimErr:
if err != nil {
return &startTime, fmsg.WrapErrorSuffix(err,
"cannot transmit shim config:")
}
killShim = func() {}
case <-time.After(shimSetupTimeout):
return &startTime, fmsg.WrapError(errors.New("timed out waiting for shim"),
"timed out waiting for shim")
}
return &startTime, nil
}

145
cmd/fshim/main.go Normal file
View File

@ -0,0 +1,145 @@
package main
import (
"errors"
"os"
"path"
"strconv"
"syscall"
init0 "git.gensokyo.uk/security/fortify/cmd/finit/ipc"
shim "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
"git.gensokyo.uk/security/fortify/helper"
"git.gensokyo.uk/security/fortify/internal"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/proc"
)
// everything beyond this point runs as unconstrained target user
// proceed with caution!
func main() {
// sharing stdout with fortify
// USE WITH CAUTION
fmsg.SetPrefix("shim")
// setting this prevents ptrace
if err := internal.PR_SET_DUMPABLE__SUID_DUMP_DISABLE(); err != nil {
fmsg.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
panic("unreachable")
}
// re-exec
if len(os.Args) > 0 && (os.Args[0] != "fshim" || len(os.Args) != 1) && path.IsAbs(os.Args[0]) {
if err := syscall.Exec(os.Args[0], []string{"fshim"}, os.Environ()); err != nil {
fmsg.Println("cannot re-exec self:", err)
// continue anyway
}
}
// check path to finit
var finitPath string
if p, ok := internal.Path(internal.Finit); !ok {
fmsg.Fatal("invalid finit path, this copy of fshim is not compiled correctly")
} else {
finitPath = p
}
// receive setup payload
var (
payload shim.Payload
closeSetup func() error
)
if f, err := proc.Receive(shim.Env, &payload); err != nil {
if errors.Is(err, proc.ErrInvalid) {
fmsg.Fatal("invalid config descriptor")
}
if errors.Is(err, proc.ErrNotSet) {
fmsg.Fatal("FORTIFY_SHIM not set")
}
fmsg.Fatalf("cannot decode shim setup payload: %v", err)
panic("unreachable")
} else {
fmsg.SetVerbose(payload.Verbose)
closeSetup = f
}
if payload.Bwrap == nil {
fmsg.Fatal("bwrap config not supplied")
}
// restore bwrap sync fd
if payload.Sync != nil {
payload.Bwrap.SetSync(os.NewFile(*payload.Sync, "sync"))
}
// close setup socket
if err := closeSetup(); err != nil {
fmsg.Println("cannot close setup pipe:", err)
// not fatal
}
var ic init0.Payload
// resolve argv0
ic.Argv = payload.Argv
if len(ic.Argv) > 0 {
// looked up from $PATH by parent
ic.Argv0 = payload.Exec[1]
} else {
// no argv, look up shell instead
var ok bool
if payload.Bwrap.SetEnv == nil {
fmsg.Fatal("no command was specified and environment is unset")
}
if ic.Argv0, ok = payload.Bwrap.SetEnv["SHELL"]; !ok {
fmsg.Fatal("no command was specified and $SHELL was unset")
}
ic.Argv = []string{ic.Argv0}
}
conf := payload.Bwrap
var extraFiles []*os.File
// serve setup payload
if fd, encoder, err := proc.Setup(&extraFiles); err != nil {
fmsg.Fatalf("cannot pipe: %v", err)
} else {
conf.SetEnv[init0.Env] = strconv.Itoa(fd)
go func() {
fmsg.VPrintln("transmitting config to init")
if err = encoder.Encode(&ic); err != nil {
fmsg.Fatalf("cannot transmit init config: %v", err)
}
}()
}
helper.BubblewrapName = payload.Exec[0] // resolved bwrap path by parent
if b, err := helper.NewBwrap(conf, nil, finitPath,
func(int, int) []string { return make([]string, 0) }); err != nil {
fmsg.Fatalf("malformed sandbox config: %v", err)
} else {
cmd := b.Unwrap()
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
cmd.ExtraFiles = extraFiles
if fmsg.Verbose() {
fmsg.VPrintln("bwrap args:", conf.Args())
}
// run and pass through exit code
if err = b.Start(); err != nil {
fmsg.Fatalf("cannot start target process: %v", err)
} else if err = b.Wait(); err != nil {
fmsg.VPrintln("wait:", err)
}
if b.Unwrap().ProcessState != nil {
fmsg.Exit(b.Unwrap().ProcessState.ExitCode())
} else {
fmsg.Exit(127)
}
}
}

154
cmd/fsu/main.go Normal file
View File

@ -0,0 +1,154 @@
package main
import (
"bytes"
"fmt"
"log"
"os"
"path"
"slices"
"strconv"
"strings"
"syscall"
)
const (
compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
fsuConfFile = "/etc/fsurc"
envShim = "FORTIFY_SHIM"
envAID = "FORTIFY_APP_ID"
envGroups = "FORTIFY_GROUPS"
PR_SET_NO_NEW_PRIVS = 0x26
)
var (
Fmain = compPoison
Fshim = compPoison
)
func main() {
log.SetFlags(0)
log.SetPrefix("fsu: ")
log.SetOutput(os.Stderr)
if os.Geteuid() != 0 {
log.Fatal("this program must be owned by uid 0 and have the setuid bit set")
}
puid := os.Getuid()
if puid == 0 {
log.Fatal("this program must not be started by root")
}
var fmain, fshim string
if p, ok := checkPath(Fmain); !ok {
log.Fatal("invalid fortify path, this copy of fsu is not compiled correctly")
} else {
fmain = p
}
if p, ok := checkPath(Fshim); !ok {
log.Fatal("invalid fshim path, this copy of fsu is not compiled correctly")
} else {
fshim = p
}
pexe := path.Join("/proc", strconv.Itoa(os.Getppid()), "exe")
if p, err := os.Readlink(pexe); err != nil {
log.Fatalf("cannot read parent executable path: %v", err)
} else if strings.HasSuffix(p, " (deleted)") {
log.Fatal("fortify executable has been deleted")
} else if p != fmain {
log.Fatal("this program must be started by fortify")
}
// uid = 1000000 +
// fid * 10000 +
// aid
uid := 1000000
// authenticate before accepting user input
if fid, ok := parseConfig(fsuConfFile, puid); !ok {
log.Fatalf("uid %d is not in the fsurc file", puid)
} else {
uid += fid * 10000
}
// allowed aid range 0 to 9999
if as, ok := os.LookupEnv(envAID); !ok {
log.Fatal("FORTIFY_APP_ID not set")
} else if aid, err := parseUint32Fast(as); err != nil || aid < 0 || aid > 9999 {
log.Fatal("invalid aid")
} else {
uid += aid
}
// pass through setup fd to shim
var shimSetupFd string
if s, ok := os.LookupEnv(envShim); !ok {
// fortify requests target uid
// print resolved uid and exit
fmt.Print(uid)
os.Exit(0)
} else if len(s) != 1 || s[0] > '9' || s[0] < '3' {
log.Fatal("FORTIFY_SHIM holds an invalid value")
} else {
shimSetupFd = s
}
// supplementary groups
var suppGroups, suppCurrent []int
if gs, ok := os.LookupEnv(envGroups); ok {
if cur, err := os.Getgroups(); err != nil {
log.Fatalf("cannot get groups: %v", err)
} else {
suppCurrent = cur
}
// parse space-separated list of group ids
gss := bytes.Split([]byte(gs), []byte{' '})
suppGroups = make([]int, len(gss)+1)
for i, s := range gss {
if gid, err := strconv.Atoi(string(s)); err != nil {
log.Fatalf("cannot parse %q: %v", string(s), err)
} else if gid > 0 && gid != uid && gid != os.Getgid() && slices.Contains(suppCurrent, gid) {
suppGroups[i] = gid
} else {
log.Fatalf("invalid gid %d", gid)
}
}
suppGroups[len(suppGroups)-1] = uid
} else {
suppGroups = []int{uid}
}
// final bounds check to catch any bugs
if uid < 1000000 || uid >= 2000000 {
panic("uid out of bounds")
}
// careful! users in the allowlist is effectively allowed to drop groups via fsu
if err := syscall.Setresgid(uid, uid, uid); err != nil {
log.Fatalf("cannot set gid: %v", err)
}
if err := syscall.Setgroups(suppGroups); err != nil {
log.Fatalf("cannot set supplementary groups: %v", err)
}
if err := syscall.Setresuid(uid, uid, uid); err != nil {
log.Fatalf("cannot set uid: %v", err)
}
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, PR_SET_NO_NEW_PRIVS, 1, 0); errno != 0 {
log.Fatalf("cannot set no_new_privs flag: %s", errno.Error())
}
if err := syscall.Exec(fshim, []string{"fshim"}, []string{envShim + "=" + shimSetupFd}); err != nil {
log.Fatalf("cannot start shim: %v", err)
}
panic("unreachable")
}
func checkPath(p string) (string, bool) {
return p, p != compPoison && p != "" && path.IsAbs(p)
}

77
cmd/fsu/parse.go Normal file
View File

@ -0,0 +1,77 @@
package main
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"strings"
"syscall"
)
func parseUint32Fast(s string) (int, error) {
sLen := len(s)
if sLen < 1 {
return -1, errors.New("zero length string")
}
if sLen > 10 {
return -1, errors.New("string too long")
}
n := 0
for i, ch := range []byte(s) {
ch -= '0'
if ch > 9 {
return -1, fmt.Errorf("invalid character '%s' at index %d", string([]byte{ch}), i)
}
n = n*10 + int(ch)
}
return n, nil
}
func parseConfig(p string, puid int) (fid int, ok bool) {
// refuse to run if fsurc is not protected correctly
if s, err := os.Stat(p); err != nil {
log.Fatal(err)
} else if s.Mode().Perm() != 0400 {
log.Fatal("bad fsurc perm")
} else if st := s.Sys().(*syscall.Stat_t); st.Uid != 0 || st.Gid != 0 {
log.Fatal("fsurc must be owned by uid 0")
}
if r, err := os.Open(p); err != nil {
log.Fatal(err)
return -1, false
} else {
s := bufio.NewScanner(r)
var line int
for s.Scan() {
line++
// <puid> <fid>
lf := strings.SplitN(s.Text(), " ", 2)
if len(lf) != 2 {
log.Fatalf("invalid entry on line %d", line)
}
var puid0 int
if puid0, err = parseUint32Fast(lf[0]); err != nil || puid0 < 1 {
log.Fatalf("invalid parent uid on line %d", line)
}
ok = puid0 == puid
if ok {
// allowed fid range 0 to 99
if fid, err = parseUint32Fast(lf[1]); err != nil || fid < 0 || fid > 99 {
log.Fatalf("invalid fortify uid on line %d", line)
}
return
}
}
if err = s.Err(); err != nil {
log.Fatalf("cannot read fsurc: %v", err)
}
return -1, false
}
}

69
cmd/fuserdb/main.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"os"
"path"
"strconv"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
func main() {
fmsg.SetPrefix("fuserdb")
const varEmpty = "/var/empty"
out := flag.String("o", "userdb", "output directory")
homeDir := flag.String("d", varEmpty, "parent of home directories")
shell := flag.String("s", "/sbin/nologin", "absolute path to subordinate user shell")
flag.Parse()
type user struct {
name string
fid int
}
users := make([]user, len(flag.Args()))
for i, s := range flag.Args() {
f := bytes.SplitN([]byte(s), []byte{':'}, 2)
if len(f) != 2 {
fmsg.Fatalf("invalid entry at index %d", i)
}
users[i].name = string(f[0])
if fid, err := strconv.Atoi(string(f[1])); err != nil {
fmsg.Fatal(err.Error())
} else {
users[i].fid = fid
}
}
if err := os.MkdirAll(*out, 0755); err != nil && !errors.Is(err, os.ErrExist) {
fmsg.Fatalf("cannot create output: %v", err)
}
for _, u := range users {
fidString := strconv.Itoa(u.fid)
for aid := 0; aid < 10000; aid++ {
userName := fmt.Sprintf("u%d_a%d", u.fid, aid)
uid := 1000000 + u.fid*10000 + aid
us := strconv.Itoa(uid)
realName := fmt.Sprintf("Fortify subordinate user %d (%s)", aid, u.name)
var homeDirectory string
if *homeDir != varEmpty {
homeDirectory = path.Join(*homeDir, "u"+fidString, "a"+strconv.Itoa(aid))
} else {
homeDirectory = varEmpty
}
writeUser(userName, uid, us, realName, homeDirectory, *shell, *out)
writeGroup(userName, uid, us, nil, *out)
}
}
fmsg.Printf("created %d entries", len(users)*2*10000)
fmsg.Exit(0)
}

64
cmd/fuserdb/payload.go Normal file
View File

@ -0,0 +1,64 @@
package main
import (
"encoding/json"
"os"
"path"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
type payloadU struct {
UserName string `json:"userName"`
Uid int `json:"uid"`
Gid int `json:"gid"`
MemberOf []string `json:"memberOf,omitempty"`
RealName string `json:"realName"`
HomeDirectory string `json:"homeDirectory"`
Shell string `json:"shell"`
}
func writeUser(userName string, uid int, us string, realName, homeDirectory, shell string, out string) {
userFileName := userName + ".user"
if f, err := os.OpenFile(path.Join(out, userFileName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
fmsg.Fatalf("cannot create %s: %v", userName, err)
} else if err = json.NewEncoder(f).Encode(&payloadU{
UserName: userName,
Uid: uid,
Gid: uid,
RealName: realName,
HomeDirectory: homeDirectory,
Shell: shell,
}); err != nil {
fmsg.Fatalf("cannot serialise %s: %v", userName, err)
} else if err = f.Close(); err != nil {
fmsg.Printf("cannot close %s: %v", userName, err)
}
if err := os.Symlink(userFileName, path.Join(out, us+".user")); err != nil {
fmsg.Fatalf("cannot link %s: %v", userName, err)
}
}
type payloadG struct {
GroupName string `json:"groupName"`
Gid int `json:"gid"`
Members []string `json:"members,omitempty"`
}
func writeGroup(groupName string, gid int, gs string, members []string, out string) {
groupFileName := groupName + ".group"
if f, err := os.OpenFile(path.Join(out, groupFileName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
fmsg.Fatalf("cannot create %s: %v", groupName, err)
} else if err = json.NewEncoder(f).Encode(&payloadG{
GroupName: groupName,
Gid: gid,
Members: members,
}); err != nil {
fmsg.Fatalf("cannot serialise %s: %v", groupName, err)
} else if err = f.Close(); err != nil {
fmsg.Printf("cannot close %s: %v", groupName, err)
}
if err := os.Symlink(groupFileName, path.Join(out, gs+".group")); err != nil {
fmsg.Fatalf("cannot link %s: %v", groupName, err)
}
}

51
comp/_fortify Normal file
View File

@ -0,0 +1,51 @@
#compdef fortify
_fortify_app() {
_path_files -g "*.(json|ftfy)"
}
_fortify_run() {
_arguments \
'--id[App ID, leave empty to disable security context app_id]:id' \
'-a[Fortify application ID]: :_numbers' \
'-g[Groups inherited by the app process]: :_groups' \
'-d[Application home directory]: :_files -/' \
'-u[Passwd name within sandbox]: :_users' \
'--wayland[Share Wayland socket]' \
'-X[Share X11 socket and allow connection]' \
'--dbus[Proxy D-Bus connection]' \
'--pulse[Share PulseAudio socket and cookie]' \
'--dbus-config[Path to D-Bus proxy config file]: :_files -g "*.json"' \
'--dbus-system[Path to system D-Bus proxy config file]: :_files -g "*.json"' \
'--mpris[Allow owning MPRIS D-Bus path]' \
'--dbus-log[Force logging in the D-Bus proxy]'
}
(( $+functions[_fortify_commands] )) || _fortify_commands()
{
local -a _fortify_cmds
_fortify_cmds=(
"app:Launch app defined by the specified config file"
"run:Configure and start a permissive default sandbox"
"ps:List active apps and their state"
"version:Show fortify version"
"license:Show full license text"
"template:Produce a config template"
"help:Show help message"
)
if (( CURRENT == 1 )); then
_describe -t commands 'fortify command' _fortify_cmds || compadd "$@"
else
local curcontext="$curcontext"
cmd="${${_fortify_cmds[(r)$words[1]:*]%%:*}}"
if (( $+functions[_fortify_$cmd] )); then
_fortify_$cmd
else
_message "no more options"
fi
fi
}
_arguments -C \
'-v[Verbose output]' \
'*::fortify command:_fortify_commands'

105
dbus/config.go Normal file
View File

@ -0,0 +1,105 @@
package dbus
import (
"encoding/json"
"errors"
"io"
"os"
)
type Config struct {
// See set 'see' policy for NAME (--see=NAME)
See []string `json:"see"`
// Talk set 'talk' policy for NAME (--talk=NAME)
Talk []string `json:"talk"`
// Own set 'own' policy for NAME (--own=NAME)
Own []string `json:"own"`
// Call set RULE for calls on NAME (--call=NAME=RULE)
Call map[string]string `json:"call"`
// Broadcast set RULE for broadcasts from NAME (--broadcast=NAME=RULE)
Broadcast map[string]string `json:"broadcast"`
Log bool `json:"log,omitempty"`
Filter bool `json:"filter"`
}
func (c *Config) Args(bus [2]string) (args []string) {
argc := 2 + len(c.See) + len(c.Talk) + len(c.Own) + len(c.Call) + len(c.Broadcast)
if c.Log {
argc++
}
if c.Filter {
argc++
}
args = make([]string, 0, argc)
args = append(args, bus[0], bus[1])
if c.Filter {
args = append(args, "--filter")
}
for _, name := range c.See {
args = append(args, "--see="+name)
}
for _, name := range c.Talk {
args = append(args, "--talk="+name)
}
for _, name := range c.Own {
args = append(args, "--own="+name)
}
for name, rule := range c.Call {
args = append(args, "--call="+name+"="+rule)
}
for name, rule := range c.Broadcast {
args = append(args, "--broadcast="+name+"="+rule)
}
if c.Log {
args = append(args, "--log")
}
return
}
func (c *Config) Load(r io.Reader) error {
return json.NewDecoder(r).Decode(&c)
}
// NewConfigFromFile opens the target config file at path and parses its contents into *Config.
func NewConfigFromFile(path string) (*Config, error) {
if f, err := os.Open(path); err != nil {
return nil, err
} else {
c := new(Config)
err1 := c.Load(f)
err = f.Close()
return c, errors.Join(err1, err)
}
}
// NewConfig returns a reference to a Config struct with optional defaults.
// If id is an empty string own defaults are omitted.
func NewConfig(id string, defaults, mpris bool) (c *Config) {
c = &Config{
Call: make(map[string]string),
Broadcast: make(map[string]string),
Filter: true,
}
if defaults {
c.Talk = []string{"org.freedesktop.DBus", "org.freedesktop.Notifications"}
c.Call["org.freedesktop.portal.*"] = "*"
c.Broadcast["org.freedesktop.portal.*"] = "@/org/freedesktop/portal/*"
if id != "" {
c.Own = []string{id + ".*"}
if mpris {
c.Own = append(c.Own, "org.mpris.MediaPlayer2."+id+".*")
}
}
}
return
}

159
dbus/config_test.go Normal file
View File

@ -0,0 +1,159 @@
package dbus_test
import (
"errors"
"os"
"path"
"reflect"
"slices"
"strings"
"testing"
"git.gensokyo.uk/security/fortify/dbus"
)
func TestConfig_Args(t *testing.T) {
for _, tc := range testCases() {
if tc.wantErr {
// args does not check for nulls
continue
}
t.Run("build arguments for "+tc.id, func(t *testing.T) {
if got := tc.c.Args(tc.bus); !slices.Equal(got, tc.want) {
t.Errorf("Args(%q) = %v, want %v",
tc.bus,
got, tc.want)
}
})
}
}
func TestNewConfigFromFile(t *testing.T) {
for _, tc := range testCases() {
name := new(strings.Builder)
name.WriteString("parse configuration file for application ")
name.WriteString(tc.id)
if tc.wantErr {
name.WriteString(" with unexpected results")
}
samplePath := path.Join("testdata", tc.id+".json")
t.Run(name.String(), func(t *testing.T) {
got, err := dbus.NewConfigFromFile(samplePath)
if errors.Is(err, os.ErrNotExist) != tc.wantErrF {
t.Errorf("NewConfigFromFile(%q) error = %v, wantErrF %v",
samplePath,
err, tc.wantErrF)
return
}
if tc.wantErrF {
return
}
if !tc.wantErr && !reflect.DeepEqual(got, tc.c) {
t.Errorf("NewConfigFromFile(%q) got = %v, want %v",
samplePath,
got, tc.c)
}
if tc.wantErr && reflect.DeepEqual(got, tc.c) {
t.Errorf("NewConfigFromFile(%q) got = %v, wantErr %v",
samplePath,
got, tc.wantErr)
}
})
}
}
func TestNewConfig(t *testing.T) {
ids := [...]string{"org.chromium.Chromium", "dev.vencord.Vesktop"}
type newTestCase struct {
id string
args [2]bool
want *dbus.Config
}
// populate tests from IDs in generic tests
tcs := make([]newTestCase, 0, (len(ids)+1)*4)
// tests for defaults without id
tcs = append(tcs,
newTestCase{"", [2]bool{false, false}, &dbus.Config{
Call: make(map[string]string),
Broadcast: make(map[string]string),
Filter: true,
}},
newTestCase{"", [2]bool{false, true}, &dbus.Config{
Call: make(map[string]string),
Broadcast: make(map[string]string),
Filter: true,
}},
newTestCase{"", [2]bool{true, false}, &dbus.Config{
Talk: []string{"org.freedesktop.DBus", "org.freedesktop.Notifications"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Filter: true,
}},
newTestCase{"", [2]bool{true, true}, &dbus.Config{
Talk: []string{"org.freedesktop.DBus", "org.freedesktop.Notifications"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Filter: true,
}},
)
for _, id := range ids {
tcs = append(tcs,
newTestCase{id, [2]bool{false, false}, &dbus.Config{
Call: make(map[string]string),
Broadcast: make(map[string]string),
Filter: true,
}},
newTestCase{id, [2]bool{false, true}, &dbus.Config{
Call: make(map[string]string),
Broadcast: make(map[string]string),
Filter: true,
}},
newTestCase{id, [2]bool{true, false}, &dbus.Config{
Talk: []string{"org.freedesktop.DBus", "org.freedesktop.Notifications"},
Own: []string{id + ".*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Filter: true,
}},
newTestCase{id, [2]bool{true, true}, &dbus.Config{
Talk: []string{"org.freedesktop.DBus", "org.freedesktop.Notifications"},
Own: []string{id + ".*", "org.mpris.MediaPlayer2." + id + ".*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Filter: true,
}},
)
}
for _, tc := range tcs {
name := new(strings.Builder)
name.WriteString("create new configuration struct")
if tc.args[0] {
name.WriteString(" with builtin defaults")
if tc.args[1] {
name.WriteString(" (mpris)")
}
}
if tc.id != "" {
name.WriteString(" for application ID ")
name.WriteString(tc.id)
}
t.Run(name.String(), func(t *testing.T) {
if gotC := dbus.NewConfig(tc.id, tc.args[0], tc.args[1]); !reflect.DeepEqual(gotC, tc.want) {
t.Errorf("NewConfig(%q, %t, %t) = %v, want %v",
tc.id, tc.args[0], tc.args[1],
gotC, tc.want)
}
})
}
}

40
dbus/dbus.go Normal file
View File

@ -0,0 +1,40 @@
// Package dbus wraps xdg-dbus-proxy and implements configuration and sandboxing of the underlying helper process.
package dbus
import (
"fmt"
"os"
"sync"
)
const (
SessionBusAddress = "DBUS_SESSION_BUS_ADDRESS"
SystemBusAddress = "DBUS_SYSTEM_BUS_ADDRESS"
)
var (
addresses [2]string
addressOnce sync.Once
)
func Address() (session, system string) {
addressOnce.Do(func() {
// resolve upstream session bus address
if addr, ok := os.LookupEnv(SessionBusAddress); !ok {
// fall back to default format
addresses[0] = fmt.Sprintf("unix:path=/run/user/%d/bus", os.Getuid())
} else {
addresses[0] = addr
}
// resolve upstream system bus address
if addr, ok := os.LookupEnv(SystemBusAddress); !ok {
// fall back to default hardcoded value
addresses[1] = "unix:path=/run/dbus/system_bus_socket"
} else {
addresses[1] = addr
}
})
return addresses[0], addresses[1]
}

215
dbus/dbus_test.go Normal file
View File

@ -0,0 +1,215 @@
package dbus_test
import (
"errors"
"strings"
"testing"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/helper"
)
func TestNew(t *testing.T) {
for _, tc := range [][2][2]string{
{
{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/1ca5d183ef4c99e74c3e544715f32702/bus"},
{"unix:path=/run/dbus/system_bus_socket", "/tmp/fortify.1971/1ca5d183ef4c99e74c3e544715f32702/system_bus_socket"},
},
{
{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/881ac3796ff3f3bf0a773824383187a0/bus"},
{"unix:path=/run/dbus/system_bus_socket", "/tmp/fortify.1971/881ac3796ff3f3bf0a773824383187a0/system_bus_socket"},
},
{
{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/3d1a5084520ef79c0c6a49a675bac701/bus"},
{"unix:path=/run/dbus/system_bus_socket", "/tmp/fortify.1971/3d1a5084520ef79c0c6a49a675bac701/system_bus_socket"},
},
{
{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/2a1639bab712799788ea0ff7aa280c35/bus"},
{"unix:path=/run/dbus/system_bus_socket", "/tmp/fortify.1971/2a1639bab712799788ea0ff7aa280c35/system_bus_socket"},
},
} {
t.Run("create instance for "+tc[0][0]+" and "+tc[1][0], func(t *testing.T) {
if got := dbus.New(tc[0], tc[1]); !got.CompareTestNew(tc[0], tc[1]) {
t.Errorf("New(%q, %q) = %v",
tc[0], tc[1],
got)
}
})
}
}
func TestProxy_Seal(t *testing.T) {
t.Run("double seal panic", func(t *testing.T) {
defer func() {
want := "dbus proxy sealed twice"
if r := recover(); r != want {
t.Errorf("Seal: panic = %q, want %q",
r, want)
}
}()
p := dbus.New([2]string{}, [2]string{})
_ = p.Seal(dbus.NewConfig("", true, false), nil)
_ = p.Seal(dbus.NewConfig("", true, false), nil)
})
ep := dbus.New([2]string{}, [2]string{})
if err := ep.Seal(nil, nil); !errors.Is(err, dbus.ErrConfig) {
t.Errorf("Seal(nil, nil) error = %v, want %v",
err, dbus.ErrConfig)
}
for id, tc := range testCasePairs() {
t.Run("create seal for "+id, func(t *testing.T) {
p := dbus.New(tc[0].bus, tc[1].bus)
if err := p.Seal(tc[0].c, tc[1].c); (errors.Is(err, helper.ErrContainsNull)) != tc[0].wantErr {
t.Errorf("Seal(%p, %p) error = %v, wantErr %v",
tc[0].c, tc[1].c,
err, tc[0].wantErr)
return
}
// rest of the tests happen for sealed instances
if tc[0].wantErr {
return
}
// build null-terminated string from wanted args
want := new(strings.Builder)
args := append(tc[0].want, tc[1].want...)
for _, arg := range args {
want.WriteString(arg)
want.WriteByte('\x00')
}
wt := p.AccessTestProxySeal()
got := new(strings.Builder)
if _, err := wt.WriteTo(got); err != nil {
t.Errorf("p.seal.WriteTo(): %v", err)
}
if want.String() != got.String() {
t.Errorf("Seal(%p, %p) seal = %v, want %v",
tc[0].c, tc[1].c,
got.String(), want.String())
}
})
}
}
func TestProxy_Start_Wait_Close_String(t *testing.T) {
t.Run("sandboxed", func(t *testing.T) {
testProxyStartWaitCloseString(t, true)
})
t.Run("direct", func(t *testing.T) {
testProxyStartWaitCloseString(t, false)
})
}
func testProxyStartWaitCloseString(t *testing.T, sandbox bool) {
for id, tc := range testCasePairs() {
// this test does not test errors
if tc[0].wantErr {
continue
}
t.Run("string for nil proxy", func(t *testing.T) {
var p *dbus.Proxy
want := "(invalid dbus proxy)"
if got := p.String(); got != want {
t.Errorf("String() = %v, want %v",
got, want)
}
})
t.Run("proxy for "+id, func(t *testing.T) {
helper.InternalReplaceExecCommand(t)
p := dbus.New(tc[0].bus, tc[1].bus)
output := new(strings.Builder)
t.Run("unsealed behaviour of "+id, func(t *testing.T) {
t.Run("unsealed string of "+id, func(t *testing.T) {
want := "(unsealed dbus proxy)"
if got := p.String(); got != want {
t.Errorf("String() = %v, want %v",
got, want)
return
}
})
t.Run("unsealed start of "+id, func(t *testing.T) {
want := "proxy not sealed"
if err := p.Start(nil, nil, sandbox); err == nil || err.Error() != want {
t.Errorf("Start() error = %v, wantErr %q",
err, errors.New(want))
return
}
})
t.Run("unsealed wait of "+id, func(t *testing.T) {
wantErr := "proxy not started"
if err := p.Wait(); err == nil || err.Error() != wantErr {
t.Errorf("Wait() error = %v, wantErr %v",
err, wantErr)
}
})
})
t.Run("seal with "+id, func(t *testing.T) {
if err := p.Seal(tc[0].c, tc[1].c); err != nil {
t.Errorf("Seal(%p, %p) error = %v, wantErr %v",
tc[0].c, tc[1].c,
err, tc[0].wantErr)
return
}
})
t.Run("sealed behaviour of "+id, func(t *testing.T) {
want := strings.Join(append(tc[0].want, tc[1].want...), " ")
if got := p.String(); got != want {
t.Errorf("String() = %v, want %v",
got, want)
return
}
t.Run("sealed start of "+id, func(t *testing.T) {
if err := p.Start(nil, output, sandbox); err != nil {
t.Errorf("Start(nil, nil) error = %v",
err)
}
t.Run("started string of "+id, func(t *testing.T) {
wantSubstr := dbus.ProxyName + " --args="
if got := p.String(); !strings.Contains(got, wantSubstr) {
t.Errorf("String() = %v, want %v",
p.String(), wantSubstr)
return
}
})
t.Run("sealed closing of "+id+" without status", func(t *testing.T) {
wantPanic := "attempted to close helper with no status pipe"
defer func() {
if r := recover(); r != wantPanic {
t.Errorf("Close() panic = %v, wantPanic %v",
r, wantPanic)
}
}()
if err := p.Close(); err != nil {
t.Errorf("Close() error = %v",
err)
}
})
t.Run("started wait of "+id, func(t *testing.T) {
if err := p.Wait(); err != nil {
t.Errorf("Wait() error = %v\noutput: %s",
err, output.String())
}
})
})
})
})
}
}

13
dbus/export_test.go Normal file
View File

@ -0,0 +1,13 @@
package dbus
import "io"
// CompareTestNew provides TestNew with comparison access to unexported Proxy fields.
func (p *Proxy) CompareTestNew(session, system [2]string) bool {
return session == p.session && system == p.system
}
// AccessTestProxySeal provides TestProxy_Seal with access to unexported Proxy seal field.
func (p *Proxy) AccessTestProxySeal() io.WriterTo {
return p.seal
}

105
dbus/proxy.go Normal file
View File

@ -0,0 +1,105 @@
package dbus
import (
"errors"
"fmt"
"io"
"sync"
"git.gensokyo.uk/security/fortify/helper"
"git.gensokyo.uk/security/fortify/helper/bwrap"
)
// ProxyName is the file name or path to the proxy program.
// Overriding ProxyName will only affect Proxy instance created after the change.
var ProxyName = "xdg-dbus-proxy"
// Proxy holds references to a xdg-dbus-proxy process, and should never be copied.
// Once sealed, configuration changes will no longer be possible and attempting to do so will result in a panic.
type Proxy struct {
helper helper.Helper
bwrap *bwrap.Config
name string
session [2]string
system [2]string
seal io.WriterTo
lock sync.RWMutex
}
func (p *Proxy) Session() [2]string {
return p.session
}
func (p *Proxy) System() [2]string {
return p.system
}
func (p *Proxy) Sealed() bool {
p.lock.RLock()
defer p.lock.RUnlock()
return p.seal != nil
}
var (
ErrConfig = errors.New("no configuration to seal")
)
func (p *Proxy) String() string {
if p == nil {
return "(invalid dbus proxy)"
}
p.lock.RLock()
defer p.lock.RUnlock()
if p.helper != nil {
return p.helper.Unwrap().String()
}
if p.seal != nil {
return p.seal.(fmt.Stringer).String()
}
return "(unsealed dbus proxy)"
}
func (p *Proxy) Bwrap() []string {
return p.bwrap.Args()
}
// Seal seals the Proxy instance.
func (p *Proxy) Seal(session, system *Config) error {
p.lock.Lock()
defer p.lock.Unlock()
if p.seal != nil {
panic("dbus proxy sealed twice")
}
if session == nil && system == nil {
return ErrConfig
}
var args []string
if session != nil {
args = append(args, session.Args(p.session)...)
}
if system != nil {
args = append(args, system.Args(p.system)...)
}
if seal, err := helper.NewCheckedArgs(args); err != nil {
return err
} else {
p.seal = seal
}
return nil
}
// New returns a reference to a new unsealed Proxy.
func New(session, system [2]string) *Proxy {
return &Proxy{name: ProxyName, session: session, system: system}
}

140
dbus/run.go Normal file
View File

@ -0,0 +1,140 @@
package dbus
import (
"errors"
"io"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"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.
// ready should be buffered and must only be received from once.
func (p *Proxy) Start(ready chan error, output io.Writer, sandbox bool) error {
p.lock.Lock()
defer p.lock.Unlock()
if p.seal == nil {
return errors.New("proxy not sealed")
}
var (
h helper.Helper
cmd *exec.Cmd
argF = func(argsFD, statFD int) []string {
if statFD == -1 {
return []string{"--args=" + strconv.Itoa(argsFD)}
} else {
return []string{"--args=" + strconv.Itoa(argsFD), "--fd=" + strconv.Itoa(statFD)}
}
}
)
if !sandbox {
h = helper.New(p.seal, p.name, argF)
cmd = h.Unwrap()
// xdg-dbus-proxy does not need to inherit the environment
cmd.Env = []string{}
} else {
// look up absolute path if name is just a file name
toolPath := p.name
if filepath.Base(p.name) == p.name {
if s, err := exec.LookPath(p.name); err == nil {
toolPath = s
}
}
// resolve libraries by parsing ldd output
var proxyDeps []*ldd.Entry
if path.IsAbs(toolPath) {
if l, err := ldd.Exec(toolPath); err != nil {
return err
} else {
proxyDeps = l
}
}
bc := &bwrap.Config{
Unshare: nil,
Hostname: "fortify-dbus",
Chdir: "/",
Clearenv: true,
NewSession: true,
DieWithParent: true,
}
// resolve proxy socket directories
bindTarget := make(map[string]struct{}, 2)
for _, ps := range []string{p.session[1], p.system[1]} {
if pd := path.Dir(ps); len(pd) > 0 {
if pd[0] == '/' {
bindTarget[pd] = struct{}{}
}
}
}
for k := range bindTarget {
bc.Bind(k, k, false, true)
}
roBindTarget := make(map[string]struct{}, 2+1+len(proxyDeps))
// xdb-dbus-proxy bin and dependencies
roBindTarget[path.Dir(toolPath)] = struct{}{}
for _, ent := range proxyDeps {
if path.IsAbs(ent.Path) {
roBindTarget[path.Dir(ent.Path)] = struct{}{}
}
}
// resolve upstream bus directories
for _, as := range []string{p.session[0], p.system[0]} {
if len(as) > 0 && strings.HasPrefix(as, "unix:path=/") {
// leave / intact
roBindTarget[path.Dir(as[10:])] = struct{}{}
}
}
for k := range roBindTarget {
bc.Bind(k, k)
}
h = helper.MustNewBwrap(bc, p.seal, toolPath, argF)
cmd = h.Unwrap()
p.bwrap = bc
}
if output != nil {
cmd.Stdout = output
cmd.Stderr = output
}
if err := h.StartNotify(ready); err != nil {
return err
}
p.helper = h
return nil
}
// Wait waits for xdg-dbus-proxy to exit or fault.
func (p *Proxy) Wait() error {
p.lock.RLock()
defer p.lock.RUnlock()
if p.helper == nil {
return errors.New("proxy not started")
}
return p.helper.Wait()
}
// Close closes the status file descriptor passed to xdg-dbus-proxy, causing it to stop.
func (p *Proxy) Close() error {
return p.helper.Close()
}

221
dbus/samples_test.go Normal file
View File

@ -0,0 +1,221 @@
package dbus_test
import (
"sync"
"git.gensokyo.uk/security/fortify/dbus"
)
var samples = []dbusTestCase{
{
"org.chromium.Chromium", &dbus.Config{
See: nil,
Talk: []string{"org.freedesktop.Notifications", "org.freedesktop.FileManager1", "org.freedesktop.ScreenSaver",
"org.freedesktop.secrets", "org.kde.kwalletd5", "org.kde.kwalletd6", "org.gnome.SessionManager"},
Own: []string{"org.chromium.Chromium.*", "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Log: false,
Filter: true,
}, false, false,
[2]string{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/12622d846cc3fe7b4c10359d01f0eb47/bus"},
[]string{
"unix:path=/run/user/1971/bus",
"/tmp/fortify.1971/12622d846cc3fe7b4c10359d01f0eb47/bus",
"--filter",
"--talk=org.freedesktop.Notifications",
"--talk=org.freedesktop.FileManager1",
"--talk=org.freedesktop.ScreenSaver",
"--talk=org.freedesktop.secrets",
"--talk=org.kde.kwalletd5",
"--talk=org.kde.kwalletd6",
"--talk=org.gnome.SessionManager",
"--own=org.chromium.Chromium.*",
"--own=org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"--own=org.mpris.MediaPlayer2.chromium.*",
"--call=org.freedesktop.portal.*=*",
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*",
},
},
{
"org.chromium.Chromium+", &dbus.Config{
See: nil,
Talk: []string{"org.bluez", "org.freedesktop.Avahi", "org.freedesktop.UPower"},
Own: nil,
Call: nil,
Broadcast: nil,
Log: false,
Filter: true,
}, false, false,
[2]string{"unix:path=/run/dbus/system_bus_socket", "/tmp/fortify.1971/12622d846cc3fe7b4c10359d01f0eb47/system_bus_socket"},
[]string{"unix:path=/run/dbus/system_bus_socket",
"/tmp/fortify.1971/12622d846cc3fe7b4c10359d01f0eb47/system_bus_socket",
"--filter",
"--talk=org.bluez",
"--talk=org.freedesktop.Avahi",
"--talk=org.freedesktop.UPower",
},
},
{
"dev.vencord.Vesktop", &dbus.Config{
See: nil,
Talk: []string{"org.freedesktop.Notifications", "org.kde.StatusNotifierWatcher"},
Own: []string{"dev.vencord.Vesktop.*", "org.mpris.MediaPlayer2.dev.vencord.Vesktop.*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Log: false,
Filter: true,
}, false, false,
[2]string{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/34c24f16a0d791d28835ededaf446033/bus"},
[]string{
"unix:path=/run/user/1971/bus",
"/tmp/fortify.1971/34c24f16a0d791d28835ededaf446033/bus",
"--filter",
"--talk=org.freedesktop.Notifications",
"--talk=org.kde.StatusNotifierWatcher",
"--own=dev.vencord.Vesktop.*",
"--own=org.mpris.MediaPlayer2.dev.vencord.Vesktop.*",
"--call=org.freedesktop.portal.*=*",
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*"},
},
{
"moe.ophivana.CrashTestDummy", &dbus.Config{
See: []string{"moe.ophivana.CrashTestDummy1"},
Talk: []string{"org.freedesktop.Notifications"},
Own: []string{"moe.ophivana.CrashTestDummy.*", "org.mpris.MediaPlayer2.moe.ophivana.CrashTestDummy.*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Log: true,
Filter: true,
}, false, false,
[2]string{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/5da7845287a936efbc2fa75d7d81e501/bus"},
[]string{
"unix:path=/run/user/1971/bus",
"/tmp/fortify.1971/5da7845287a936efbc2fa75d7d81e501/bus",
"--filter",
"--see=moe.ophivana.CrashTestDummy1",
"--talk=org.freedesktop.Notifications",
"--own=moe.ophivana.CrashTestDummy.*",
"--own=org.mpris.MediaPlayer2.moe.ophivana.CrashTestDummy.*",
"--call=org.freedesktop.portal.*=*",
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*",
"--log"},
},
{
"moe.ophivana.CrashTestDummy1", &dbus.Config{
See: []string{"moe.ophivana.CrashTestDummy"},
Talk: []string{"org.freedesktop.Notifications"},
Own: []string{"moe.ophivana.CrashTestDummy1.*", "org.mpris.MediaPlayer2.moe.ophivana.CrashTestDummy1.*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Log: true,
Filter: true,
}, false, true,
[2]string{"unix:path=/run/user/1971/bus", "/tmp/fortify.1971/5da7845287a936efbc2fa75d7d81e501/bus"},
[]string{
"unix:path=/run/user/1971/bus",
"/tmp/fortify.1971/5da7845287a936efbc2fa75d7d81e501/bus",
"--filter",
"--see=moe.ophivana.CrashTestDummy",
"--talk=org.freedesktop.Notifications",
"--own=moe.ophivana.CrashTestDummy1.*",
"--own=org.mpris.MediaPlayer2.moe.ophivana.CrashTestDummy1.*",
"--call=org.freedesktop.portal.*=*",
"--broadcast=org.freedesktop.portal.*=@/org/freedesktop/portal/*",
"--log"},
},
}
type dbusTestCase struct {
id string
c *dbus.Config
wantErr bool
wantErrF bool
bus [2]string
want []string
}
var (
testCasesV []dbusTestCase
testCasePairsV map[string][2]dbusTestCase
testCaseOnce sync.Once
)
func testCases() []dbusTestCase {
testCaseOnce.Do(testCaseGenerate)
return testCasesV
}
func testCasePairs() map[string][2]dbusTestCase {
testCaseOnce.Do(testCaseGenerate)
return testCasePairsV
}
func injectNulls(t *[]string) {
f := make([]string, len(*t))
for i := range f {
f[i] = "\x00" + (*t)[i] + "\x00"
}
*t = f
}
func testCaseGenerate() {
// create null-injected test cases
testCasesV = make([]dbusTestCase, len(samples)*2)
for i := range samples {
testCasesV[i] = samples[i]
testCasesV[len(samples)+i] = samples[i]
testCasesV[len(samples)+i].c = new(dbus.Config)
*testCasesV[len(samples)+i].c = *samples[i].c
// inject nulls
fi := &testCasesV[len(samples)+i]
fi.wantErr = true
injectNulls(&fi.c.See)
injectNulls(&fi.c.Talk)
injectNulls(&fi.c.Own)
}
// enumerate test case pairs
var pc int
for _, tc := range samples {
if tc.id != "" {
pc++
}
}
testCasePairsV = make(map[string][2]dbusTestCase, pc)
for i, tc := range testCasesV {
if tc.id == "" {
continue
}
// skip already enumerated system bus test
if tc.id[len(tc.id)-1] == '+' {
continue
}
ftp := [2]dbusTestCase{tc}
// system proxy tests always place directly after its user counterpart with id ending in +
if i+1 < len(testCasesV) && testCasesV[i+1].id[len(testCasesV[i+1].id)-1] == '+' {
// attach system bus config
ftp[1] = testCasesV[i+1]
// check for misplaced/mismatching tests
if ftp[0].wantErr != ftp[1].wantErr || ftp[0].id+"+" != ftp[1].id {
panic("mismatching session/system pairing")
}
}
k := tc.id
if tc.wantErr {
k = "malformed_" + k
}
testCasePairsV[k] = ftp
}
}

11
dbus/stub_test.go Normal file
View File

@ -0,0 +1,11 @@
package dbus_test
import (
"testing"
"git.gensokyo.uk/security/fortify/helper"
)
func TestHelperChildStub(t *testing.T) {
helper.InternalChildStub()
}

18
dbus/testdata/dev.vencord.Vesktop.json vendored Normal file
View File

@ -0,0 +1,18 @@
{
"talk":[
"org.freedesktop.Notifications",
"org.kde.StatusNotifierWatcher"
],
"own":[
"dev.vencord.Vesktop.*",
"org.mpris.MediaPlayer2.dev.vencord.Vesktop.*"
],
"call":{
"org.freedesktop.portal.*":"*"
},
"broadcast":{
"org.freedesktop.portal.*":"@/org/freedesktop/portal/*"
},
"filter":true
}

View File

@ -0,0 +1,21 @@
{
"see": [
"moe.ophivana.CrashTestDummy1"
],
"talk":[
"org.freedesktop.Notifications"
],
"own":[
"moe.ophivana.CrashTestDummy.*",
"org.mpris.MediaPlayer2.moe.ophivana.CrashTestDummy.*"
],
"call":{
"org.freedesktop.portal.*":"*"
},
"broadcast":{
"org.freedesktop.portal.*":"@/org/freedesktop/portal/*"
},
"log": true,
"filter":true
}

View File

@ -0,0 +1,9 @@
{
"talk":[
"org.bluez",
"org.freedesktop.Avahi",
"org.freedesktop.UPower"
],
"filter":true
}

View File

@ -0,0 +1,24 @@
{
"talk":[
"org.freedesktop.Notifications",
"org.freedesktop.FileManager1",
"org.freedesktop.ScreenSaver",
"org.freedesktop.secrets",
"org.kde.kwalletd5",
"org.kde.kwalletd6",
"org.gnome.SessionManager"
],
"own":[
"org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*"
],
"call":{
"org.freedesktop.portal.*":"*"
},
"broadcast":{
"org.freedesktop.portal.*":"@/org/freedesktop/portal/*"
},
"filter":true
}

1
dist/fsurc.default vendored Normal file
View File

@ -0,0 +1 @@
1000 0

10
dist/install.sh vendored Executable file
View File

@ -0,0 +1,10 @@
#!/bin/sh
cd "$(dirname -- "$0")" || exit 1
install -vDm0755 "bin/fortify" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fortify"
install -vDm0755 "bin/fshim" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/fshim"
install -vDm0755 "bin/finit" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/finit"
install -vDm0755 "bin/fuserdb" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/fuserdb"
install -vDm6511 "bin/fsu" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fsu"
install -vDm0400 "fsurc.default" "${FORTIFY_INSTALL_PREFIX}/etc/fsurc"

19
dist/release.sh vendored Executable file
View File

@ -0,0 +1,19 @@
#!/bin/sh -e
cd "$(dirname -- "$0")/.."
VERSION="${FORTIFY_VERSION:-untagged}"
pname="fortify-${VERSION}"
out="dist/${pname}"
mkdir -p "${out}"
cp "README.md" "dist/fsurc.default" "dist/install.sh" "${out}"
go build -v -o "${out}/bin/" -ldflags "-s -w
-X git.gensokyo.uk/security/fortify/internal.Version=${VERSION}
-X git.gensokyo.uk/security/fortify/internal.Fsu=/usr/bin/fsu
-X git.gensokyo.uk/security/fortify/internal.Finit=/usr/libexec/fortify/finit
-X main.Fmain=/usr/bin/fortify
-X main.Fshim=/usr/libexec/fortify/fshim" ./...
rm -f "./${out}.tar.gz" && tar -C dist -czf "${out}.tar.gz" "${pname}"
rm -rf "./${out}"
sha512sum "${out}.tar.gz" > "${out}.tar.gz.sha512"

55
error.go Normal file
View File

@ -0,0 +1,55 @@
package main
import (
"errors"
"git.gensokyo.uk/security/fortify/internal/app"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
func logWaitError(err error) {
var e *fmsg.BaseError
if !fmsg.AsBaseError(err, &e) {
fmsg.Println("wait failed:", err)
} else {
// Wait only returns either *app.ProcessError or *app.StateStoreError wrapped in a *app.BaseError
var se *app.StateStoreError
if !errors.As(err, &se) {
// does not need special handling
fmsg.Print(e.Message())
} else {
// inner error are either unwrapped store errors
// or joined errors returned by *appSealTx revert
// wrapped in *app.BaseError
var ej app.RevertCompoundError
if !errors.As(se.InnerErr, &ej) {
// does not require special handling
fmsg.Print(e.Message())
} else {
errs := ej.Unwrap()
// every error here is wrapped in *app.BaseError
for _, ei := range errs {
var eb *fmsg.BaseError
if !errors.As(ei, &eb) {
// unreachable
fmsg.Println("invalid error type returned by revert:", ei)
} else {
// print inner *app.BaseError message
fmsg.Print(eb.Message())
}
}
}
}
}
}
func logBaseError(err error, message string) {
var e *fmsg.BaseError
if fmsg.AsBaseError(err, &e) {
fmsg.Print(e.Message())
} else {
fmsg.Println(message, err)
}
}

30
flake.lock generated
View File

@ -1,23 +1,45 @@
{ {
"nodes": { "nodes": {
"home-manager": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1733951536,
"narHash": "sha256-Zb5ZCa7Xj+0gy5XVXINTSr71fCfAv+IKtmIXNrykT54=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "1318c3f3b068cdcea922fa7c1a0a1f0c96c22f5f",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "release-24.11",
"repo": "home-manager",
"type": "github"
}
},
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1717179513, "lastModified": 1734298236,
"narHash": "sha256-vboIEwIQojofItm2xGCdZCzW96U85l9nDW3ifMuAIdM=", "narHash": "sha256-aWhhqY44xBjMoO9r5fyPp5u8tqUNWRZ/m/P+abMSs5c=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "63dacb46bf939521bdc93981b4cbb7ecb58427a0", "rev": "eb919d9300b6a18f8583f58aef16db458fbd7bec",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "NixOS", "owner": "NixOS",
"ref": "24.05", "ref": "nixos-24.11-small",
"repo": "nixpkgs", "repo": "nixpkgs",
"type": "github" "type": "github"
} }
}, },
"root": { "root": {
"inputs": { "inputs": {
"home-manager": "home-manager",
"nixpkgs": "nixpkgs" "nixpkgs": "nixpkgs"
} }
} }

164
flake.nix
View File

@ -1,56 +1,152 @@
{ {
description = "ego development environment"; description = "fortify sandbox tool and nixos module";
inputs = { inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/24.05"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11-small";
home-manager = {
url = "github:nix-community/home-manager/release-24.11";
inputs.nixpkgs.follows = "nixpkgs";
};
}; };
outputs = outputs =
{ self, nixpkgs }: {
self,
nixpkgs,
home-manager,
}:
let let
supportedSystems = [ "x86_64-linux" ]; supportedSystems = [
forAllSystems = f: nixpkgs.lib.genAttrs supportedSystems (system: f system); "aarch64-linux"
"i686-linux"
"x86_64-linux"
];
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
nixpkgsFor = forAllSystems (system: import nixpkgs { inherit system; });
in in
{ {
devShells = forAllSystems ( nixosModules.fortify = import ./nixos.nix;
checks = forAllSystems (
system: system:
let let
pkgs = import nixpkgs { inherit system; }; pkgs = nixpkgsFor.${system};
in
{
default =
let
inherit (pkgs) inherit (pkgs)
mkShell runCommandLocal
buildGoModule callPackage
acl nixfmt-rfc-style
xorg deadnix
statix
; ;
in in
mkShell { {
packages = [ check-formatting =
(buildGoModule rec { runCommandLocal "check-formatting" { nativeBuildInputs = [ nixfmt-rfc-style ]; }
pname = "ego"; ''
version = "0.0.0-flake"; cd ${./.}
src = ./.; echo "running nixfmt..."
vendorHash = null; # we have no dependencies :3 nixfmt --check .
ldflags = [ touch $out
"-s" '';
"-w"
"-X"
"main.Version=v${version}"
];
buildInputs = [ check-lint =
acl runCommandLocal "check-lint"
xorg.libxcb {
nativeBuildInputs = [
deadnix
statix
]; ];
}) }
]; ''
}; cd ${./.}
echo "running deadnix..."
deadnix --fail
echo "running statix..."
statix check .
touch $out
'';
nixos-tests = callPackage ./test.nix { inherit system self home-manager; };
} }
); );
packages = forAllSystems (
system:
let
pkgs = nixpkgsFor.${system};
in
{
default = self.packages.${system}.fortify;
fortify = pkgs.callPackage ./package.nix { };
}
);
devShells = forAllSystems (system: {
default = nixpkgsFor.${system}.mkShell {
buildInputs = with nixpkgsFor.${system}; self.packages.${system}.fortify.buildInputs;
};
fhs = nixpkgsFor.${system}.buildFHSEnv {
pname = "fortify-fhs";
inherit (self.packages.${system}.fortify) version;
targetPkgs =
pkgs: with pkgs; [
go
gcc
pkg-config
acl
wayland
wayland-scanner
wayland-protocols
xorg.libxcb
];
extraOutputsToInstall = [ "dev" ];
profile = ''
export PKG_CONFIG_PATH="/usr/share/pkgconfig:$PKG_CONFIG_PATH"
'';
};
withPackage = nixpkgsFor.${system}.mkShell {
buildInputs =
with nixpkgsFor.${system};
self.packages.${system}.fortify.buildInputs ++ [ self.packages.${system}.fortify ];
};
generateDoc =
let
pkgs = nixpkgsFor.${system};
inherit (pkgs) lib;
doc =
let
eval = lib.evalModules {
specialArgs = {
inherit pkgs;
};
modules = [ ./options.nix ];
};
cleanEval = lib.filterAttrsRecursive (n: _: n != "_module") eval;
in
pkgs.nixosOptionsDoc { inherit (cleanEval) options; };
docText = pkgs.runCommand "fortify-module-docs.md" { } ''
cat ${doc.optionsCommonMark} > $out
sed -i '/*Declared by:*/,+1 d' $out
'';
in
nixpkgsFor.${system}.mkShell {
shellHook = ''
exec cat ${docText} > options.md
'';
};
});
}; };
} }

242
fst/config.go Normal file
View File

@ -0,0 +1,242 @@
package fst
import (
"errors"
"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"
// Config is used to seal an *App
type Config struct {
// D-Bus application ID
ID string `json:"id"`
// value passed through to the child process as its argv
Command []string `json:"command"`
// child confinement configuration
Confinement ConfinementConfig `json:"confinement"`
}
// ConfinementConfig defines fortified child's confinement
type ConfinementConfig struct {
// numerical application id, determines uid in the init namespace
AppID int `json:"app_id"`
// list of supplementary groups to inherit
Groups []string `json:"groups"`
// passwd username in the sandbox, defaults to chronos
Username string `json:"username,omitempty"`
// home directory in sandbox, empty for outer
Inner string `json:"home_inner"`
// home directory in init namespace
Outer string `json:"home"`
// bwrap sandbox confinement configuration
Sandbox *SandboxConfig `json:"sandbox"`
// reference to a system D-Bus proxy configuration,
// nil value disables system bus proxy
SystemBus *dbus.Config `json:"system_bus,omitempty"`
// reference to a session D-Bus proxy configuration,
// nil value makes session bus proxy assume built-in defaults
SessionBus *dbus.Config `json:"session_bus,omitempty"`
// child capability enablements
Enablements system.Enablements `json:"enablements"`
}
// SandboxConfig describes resources made available to the sandbox.
type SandboxConfig struct {
// unix hostname within sandbox
Hostname string `json:"hostname,omitempty"`
// userns availability within sandbox
UserNS bool `json:"userns,omitempty"`
// share net namespace
Net bool `json:"net,omitempty"`
// share all devices
Dev bool `json:"dev,omitempty"`
// do not run in new session
NoNewSession bool `json:"no_new_session,omitempty"`
// map target user uid to privileged user uid in the user namespace
MapRealUID bool `json:"map_real_uid"`
// direct access to wayland socket
DirectWayland bool `json:"direct_wayland,omitempty"`
// final environment variables
Env map[string]string `json:"env"`
// sandbox host filesystem access
Filesystem []*FilesystemConfig `json:"filesystem"`
// symlinks created inside the sandbox
Link [][2]string `json:"symlink"`
// automatically set up /etc symlinks
AutoEtc bool `json:"auto_etc"`
// paths to override by mounting tmpfs over them
Override []string `json:"override"`
}
type FilesystemConfig struct {
// mount point in sandbox, same as src if empty
Dst string `json:"dst,omitempty"`
// host filesystem path to make available to sandbox
Src string `json:"src"`
// write access
Write bool `json:"write,omitempty"`
// device access
Device bool `json:"dev,omitempty"`
// exit if unable to share
Must bool `json:"require,omitempty"`
}
// Bwrap returns the address of the corresponding bwrap.Config to s.
// Note that remaining tmpfs entries must be queued by the caller prior to launch.
func (s *SandboxConfig) Bwrap(os linux.System) (*bwrap.Config, error) {
if s == nil {
return nil, errors.New("nil sandbox config")
}
var uid int
if !s.MapRealUID {
uid = 65534
} else {
uid = os.Geteuid()
}
conf := (&bwrap.Config{
Net: s.Net,
UserNS: s.UserNS,
Hostname: s.Hostname,
Clearenv: true,
SetEnv: s.Env,
NewSession: !s.NoNewSession,
DieWithParent: true,
AsInit: true,
// initialise map
Chmod: make(bwrap.ChmodConfig),
}).
SetUID(uid).SetGID(uid).
Procfs("/proc").
Tmpfs(fTmp, 4*1024)
if !s.Dev {
conf.DevTmpfs("/dev").Mqueue("/dev/mqueue")
} else {
conf.Bind("/dev", "/dev", false, true, true)
}
if !s.AutoEtc {
conf.Dir("/etc")
}
for _, c := range s.Filesystem {
if c == nil {
continue
}
src := c.Src
dest := c.Dst
if c.Dst == "" {
dest = c.Src
}
conf.Bind(src, dest, !c.Must, c.Write, c.Device)
}
for _, l := range s.Link {
conf.Symlink(l[0], l[1])
}
if s.AutoEtc {
conf.Bind("/etc", fTmp+"/etc")
// link host /etc contents to prevent passwd/group from being overwritten
if d, err := os.ReadDir("/etc"); err != nil {
return nil, err
} else {
for _, ent := range d {
name := ent.Name()
switch name {
case "passwd":
case "group":
case "mtab":
conf.Symlink("/proc/mounts", "/etc/"+name)
default:
conf.Symlink(fTmp+"/etc/"+name, "/etc/"+name)
}
}
}
}
return conf, nil
}
// Template returns a fully populated instance of Config.
func Template() *Config {
return &Config{
ID: "org.chromium.Chromium",
Command: []string{
"chromium",
"--ignore-gpu-blocklist",
"--disable-smooth-scrolling",
"--enable-features=UseOzonePlatform",
"--ozone-platform=wayland",
},
Confinement: ConfinementConfig{
AppID: 9,
Groups: []string{"video"},
Username: "chronos",
Outer: "/var/lib/persist/home/org.chromium.Chromium",
Inner: "/var/lib/fortify",
Sandbox: &SandboxConfig{
Hostname: "localhost",
UserNS: true,
Net: true,
NoNewSession: true,
MapRealUID: true,
Dev: true,
DirectWayland: false,
// example API credentials pulled from Google Chrome
// DO NOT USE THESE IN A REAL BROWSER
Env: map[string]string{
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT",
},
Filesystem: []*FilesystemConfig{
{Src: "/nix/store"},
{Src: "/run/current-system"},
{Src: "/run/opengl-driver"},
{Src: "/var/db/nix-channels"},
{Src: "/home/chronos", Write: true, Must: true},
{Src: "/dev/dri", Device: true},
},
Link: [][2]string{{"/run/user/65534", "/run/user/150"}},
AutoEtc: true,
Override: []string{"/var/run/nscd"},
},
SystemBus: &dbus.Config{
See: nil,
Talk: []string{"org.bluez", "org.freedesktop.Avahi", "org.freedesktop.UPower"},
Own: nil,
Call: nil,
Broadcast: nil,
Log: false,
Filter: true,
},
SessionBus: &dbus.Config{
See: nil,
Talk: []string{"org.freedesktop.Notifications", "org.freedesktop.FileManager1", "org.freedesktop.ScreenSaver",
"org.freedesktop.secrets", "org.kde.kwalletd5", "org.kde.kwalletd6", "org.gnome.SessionManager"},
Own: []string{"org.chromium.Chromium.*", "org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*"},
Call: map[string]string{"org.freedesktop.portal.*": "*"},
Broadcast: map[string]string{"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"},
Log: false,
Filter: true,
},
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
},
}
}

48
fst/id.go Normal file
View 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
View 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
View File

@ -0,0 +1,2 @@
// Package fst exports shared fortify types.
package fst

2
go.mod
View File

@ -1,3 +1,3 @@
module git.ophivana.moe/cat/ego module git.gensokyo.uk/security/fortify
go 1.22 go 1.22

66
helper/args.go Normal file
View File

@ -0,0 +1,66 @@
package helper
import (
"errors"
"io"
"strings"
)
var (
ErrContainsNull = errors.New("argument contains null character")
)
type argsWt []string
// checks whether any element contains the null character
// must be called before args use and args must not be modified after call
func (a argsWt) check() error {
for _, arg := range a {
for _, b := range arg {
if b == '\x00' {
return ErrContainsNull
}
}
}
return nil
}
func (a argsWt) WriteTo(w io.Writer) (int64, error) {
// assuming already checked
nt := 0
// write null terminated arguments
for _, arg := range a {
n, err := w.Write([]byte(arg + "\x00"))
nt += n
if err != nil {
return int64(nt), err
}
}
return int64(nt), nil
}
func (a argsWt) String() string {
return strings.Join(a, " ")
}
// NewCheckedArgs returns a checked argument writer for args.
// Callers must not retain any references to args.
func NewCheckedArgs(args []string) (io.WriterTo, error) {
a := argsWt(args)
return a, a.check()
}
// MustNewCheckedArgs returns a checked argument writer for args and panics if check fails.
// Callers must not retain any references to args.
func MustNewCheckedArgs(args []string) io.WriterTo {
a, err := NewCheckedArgs(args)
if err != nil {
panic(err.Error())
}
return a
}

40
helper/args_test.go Normal file
View File

@ -0,0 +1,40 @@
package helper_test
import (
"errors"
"fmt"
"strings"
"testing"
"git.gensokyo.uk/security/fortify/helper"
)
func Test_argsFD_String(t *testing.T) {
wantString := strings.Join(wantArgs, " ")
if got := argsWt.(fmt.Stringer).String(); got != wantString {
t.Errorf("String(): got %v; want %v",
got, wantString)
}
}
func TestNewCheckedArgs(t *testing.T) {
args := []string{"\x00"}
if _, err := helper.NewCheckedArgs(args); !errors.Is(err, helper.ErrContainsNull) {
t.Errorf("NewCheckedArgs(%q) error = %v, wantErr %v",
args,
err, helper.ErrContainsNull)
}
t.Run("must panic", func(t *testing.T) {
badPayload := []string{"\x00"}
defer func() {
wantPanic := "argument contains null character"
if r := recover(); r != wantPanic {
t.Errorf("MustNewCheckedArgs(%q) panic = %v, wantPanic %v",
badPayload,
r, wantPanic)
}
}()
helper.MustNewCheckedArgs(badPayload)
})
}

151
helper/bwrap.go Normal file
View File

@ -0,0 +1,151 @@
package helper
import (
"errors"
"io"
"os"
"os/exec"
"strconv"
"sync"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/proc"
)
// BubblewrapName is the file name or path to bubblewrap.
var BubblewrapName = "bwrap"
type bubblewrap struct {
// bwrap child file name
name string
// bwrap pipes
p *pipes
// sync pipe
sync *os.File
// returns an array of arguments passed directly
// to the child process spawned by bwrap
argF func(argsFD, statFD int) []string
// pipes received by the child
// nil if no pipes are required
cp *pipes
lock sync.RWMutex
*exec.Cmd
}
func (b *bubblewrap) StartNotify(ready chan error) error {
b.lock.Lock()
defer b.lock.Unlock()
if ready != nil && b.cp == nil {
panic("attempted to start with status monitoring on a bwrap child initialised without pipes")
}
// Check for doubled Start calls before we defer failure cleanup. If the prior
// call to Start succeeded, we don't want to spuriously close its pipes.
if b.Cmd.Process != nil {
return errors.New("exec: already started")
}
// prepare bwrap pipe and args
if argsFD, _, err := b.p.prepareCmd(b.Cmd); err != nil {
return err
} else {
b.Cmd.Args = append(b.Cmd.Args, "--args", strconv.Itoa(argsFD), "--", b.name)
}
// prepare child args and pipes if enabled
if b.cp != nil {
b.cp.ready = ready
if argsFD, statFD, err := b.cp.prepareCmd(b.Cmd); err != nil {
return err
} else {
b.Cmd.Args = append(b.Cmd.Args, b.argF(argsFD, statFD)...)
}
} else {
b.Cmd.Args = append(b.Cmd.Args, b.argF(-1, -1)...)
}
if ready != nil {
b.Cmd.Env = append(b.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=1")
} else if b.cp != nil {
b.Cmd.Env = append(b.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=0")
} else {
b.Cmd.Env = append(b.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=-1")
}
if b.sync != nil {
b.Cmd.Args = append(b.Cmd.Args, "--sync-fd", strconv.Itoa(int(proc.ExtraFile(b.Cmd, b.sync))))
}
if err := b.Cmd.Start(); err != nil {
return err
}
// write bwrap args first
if err := b.p.readyWriteArgs(); err != nil {
return err
}
// write child args if enabled
if b.cp != nil {
if err := b.cp.readyWriteArgs(); err != nil {
return err
}
}
return nil
}
func (b *bubblewrap) Close() error {
if b.cp == nil {
panic("attempted to close bwrap child initialised without pipes")
}
return b.cp.closeStatus()
}
func (b *bubblewrap) Start() error {
return b.StartNotify(nil)
}
func (b *bubblewrap) Unwrap() *exec.Cmd {
return b.Cmd
}
// MustNewBwrap initialises a new Bwrap instance with wt as the null-terminated argument writer.
// If wt is nil, the child process spawned by bwrap will not get an argument pipe.
// Function argF returns an array of arguments passed directly to the child process.
func MustNewBwrap(conf *bwrap.Config, wt io.WriterTo, name string, argF func(argsFD, statFD int) []string) Helper {
b, err := NewBwrap(conf, wt, name, argF)
if err != nil {
panic(err.Error())
} else {
return b
}
}
// NewBwrap initialises a new Bwrap instance with wt as the null-terminated argument writer.
// If wt is nil, the child process spawned by bwrap will not get an argument pipe.
// Function argF returns an array of arguments passed directly to the child process.
func NewBwrap(conf *bwrap.Config, wt io.WriterTo, name string, argF func(argsFD, statFD int) []string) (Helper, error) {
b := new(bubblewrap)
if args, err := NewCheckedArgs(conf.Args()); err != nil {
return nil, err
} else {
b.p = &pipes{args: args}
}
b.sync = conf.Sync()
b.argF = argF
b.name = name
if wt != nil {
b.cp = &pipes{args: wt}
}
b.Cmd = execCommand(BubblewrapName)
return b, nil
}

77
helper/bwrap/arg.go Normal file
View File

@ -0,0 +1,77 @@
package bwrap
import "encoding/gob"
type Builder interface {
Len() int
Append(args *[]string)
}
type FSBuilder interface {
Path() string
Builder
}
func init() {
gob.Register(new(pairF))
gob.Register(new(stringF))
}
type pairF [3]string
func (p *pairF) Path() string {
return p[2]
}
func (p *pairF) Len() int {
return len(p) // compiler replaces this with 3
}
func (p *pairF) Append(args *[]string) {
*args = append(*args, p[0], p[1], p[2])
}
type stringF [2]string
func (s stringF) Path() string {
return s[1]
}
func (s stringF) Len() int {
return len(s) // compiler replaces this with 2
}
func (s stringF) Append(args *[]string) {
*args = append(*args, s[0], s[1])
}
// Args returns a slice of bwrap args corresponding to c.
func (c *Config) Args() (args []string) {
builders := []Builder{
c.boolArgs(),
c.intArgs(),
c.stringArgs(),
c.pairArgs(),
}
// copy FSBuilder slice to builder slice
fb := make([]Builder, len(c.Filesystem)+1)
for i, f := range c.Filesystem {
fb[i] = f
}
fb[len(fb)-1] = c.Chmod
builders = append(builders, fb...)
// accumulate arg count
argc := 0
for _, b := range builders {
argc += b.Len()
}
args = make([]string, 0, argc)
for _, b := range builders {
b.Append(&args)
}
return
}

View File

@ -0,0 +1,13 @@
package bwrap
const (
Tmpfs = iota
Dir
Symlink
)
var awkwardArgs = [...]string{
Tmpfs: "--tmpfs",
Dir: "--dir",
Symlink: "--symlink",
}

View File

@ -0,0 +1,81 @@
package bwrap
const (
UnshareAll = iota
UnshareUser
UnshareIPC
UnsharePID
UnshareNet
UnshareUTS
UnshareCGroup
ShareNet
UserNS
Clearenv
NewSession
DieWithParent
AsInit
)
var boolArgs = [...][]string{
UnshareAll: {"--unshare-all", "--unshare-user"},
UnshareUser: {"--unshare-user"},
UnshareIPC: {"--unshare-ipc"},
UnsharePID: {"--unshare-pid"},
UnshareNet: {"--unshare-net"},
UnshareUTS: {"--unshare-uts"},
UnshareCGroup: {"--unshare-cgroup"},
ShareNet: {"--share-net"},
UserNS: {"--disable-userns", "--assert-userns-disabled"},
Clearenv: {"--clearenv"},
NewSession: {"--new-session"},
DieWithParent: {"--die-with-parent"},
AsInit: {"--as-pid-1"},
}
func (c *Config) boolArgs() Builder {
b := boolArg{
UserNS: !c.UserNS,
Clearenv: c.Clearenv,
NewSession: c.NewSession,
DieWithParent: c.DieWithParent,
AsInit: c.AsInit,
}
if c.Unshare == nil {
b[UnshareAll] = true
b[ShareNet] = c.Net
} else {
b[UnshareUser] = c.Unshare.User
b[UnshareIPC] = c.Unshare.IPC
b[UnsharePID] = c.Unshare.PID
b[UnshareNet] = c.Unshare.Net
b[UnshareUTS] = c.Unshare.UTS
b[UnshareCGroup] = c.Unshare.CGroup
}
return &b
}
type boolArg [len(boolArgs)]bool
func (b *boolArg) Len() (l int) {
for i, v := range b {
if v {
l += len(boolArgs[i])
}
}
return
}
func (b *boolArg) Append(args *[]string) {
for i, v := range b {
if v {
*args = append(*args, boolArgs[i]...)
}
}
}

View File

@ -0,0 +1,47 @@
package bwrap
import "strconv"
const (
UID = iota
GID
Perms
Size
)
var intArgs = [...]string{
UID: "--uid",
GID: "--gid",
Perms: "--perms",
Size: "--size",
}
func (c *Config) intArgs() Builder {
// Arg types:
// Perms
// are handled by the sequential builder
return &intArg{
UID: c.UID,
GID: c.GID,
}
}
type intArg [len(intArgs)]*int
func (n *intArg) Len() (l int) {
for _, v := range n {
if v != nil {
l += 2
}
}
return
}
func (n *intArg) Append(args *[]string) {
for i, v := range n {
if v != nil {
*args = append(*args, intArgs[i], strconv.Itoa(*v))
}
}
}

View File

@ -0,0 +1,73 @@
package bwrap
import (
"slices"
)
const (
SetEnv = iota
Bind
BindTry
DevBind
DevBindTry
ROBind
ROBindTry
Chmod
)
var pairArgs = [...]string{
SetEnv: "--setenv",
Bind: "--bind",
BindTry: "--bind-try",
DevBind: "--dev-bind",
DevBindTry: "--dev-bind-try",
ROBind: "--ro-bind",
ROBindTry: "--ro-bind-try",
Chmod: "--chmod",
}
func (c *Config) pairArgs() Builder {
var n pairArg
n[SetEnv] = make([][2]string, len(c.SetEnv))
keys := make([]string, 0, len(c.SetEnv))
for k := range c.SetEnv {
keys = append(keys, k)
}
slices.Sort(keys)
for i, k := range keys {
n[SetEnv][i] = [2]string{k, c.SetEnv[k]}
}
// Arg types:
// Bind
// BindTry
// DevBind
// DevBindTry
// ROBind
// ROBindTry
// Chmod
// are handled by the sequential builder
return &n
}
type pairArg [len(pairArgs)][][2]string
func (p *pairArg) Len() (l int) {
for _, v := range p {
l += len(v) * 3
}
return
}
func (p *pairArg) Append(args *[]string) {
for i, arg := range p {
for _, v := range arg {
*args = append(*args, pairArgs[i], v[0], v[1])
}
}
}

View File

@ -0,0 +1,65 @@
package bwrap
const (
Hostname = iota
Chdir
UnsetEnv
LockFile
RemountRO
Procfs
DevTmpfs
Mqueue
)
var stringArgs = [...]string{
Hostname: "--hostname",
Chdir: "--chdir",
UnsetEnv: "--unsetenv",
LockFile: "--lock-file",
RemountRO: "--remount-ro",
Procfs: "--proc",
DevTmpfs: "--dev",
Mqueue: "--mqueue",
}
func (c *Config) stringArgs() Builder {
n := stringArg{
UnsetEnv: c.UnsetEnv,
LockFile: c.LockFile,
}
if c.Hostname != "" {
n[Hostname] = []string{c.Hostname}
}
if c.Chdir != "" {
n[Chdir] = []string{c.Chdir}
}
// Arg types:
// RemountRO
// Procfs
// DevTmpfs
// Mqueue
// are handled by the sequential builder
return &n
}
type stringArg [len(stringArgs)][]string
func (s *stringArg) Len() (l int) {
for _, arg := range s {
l += len(arg) * 2
}
return
}
func (s *stringArg) Append(args *[]string) {
for i, arg := range s {
for _, v := range arg {
*args = append(*args, stringArgs[i], v)
}
}
}

205
helper/bwrap/config.go Normal file
View File

@ -0,0 +1,205 @@
package bwrap
import (
"encoding/gob"
"os"
"strconv"
)
func init() {
gob.Register(new(PermConfig[SymlinkConfig]))
gob.Register(new(PermConfig[*TmpfsConfig]))
}
type Config struct {
// unshare every namespace we support by default if nil
// (--unshare-all)
Unshare *UnshareConfig `json:"unshare,omitempty"`
// retain the network namespace (can only combine with nil Unshare)
// (--share-net)
Net bool `json:"net"`
// disable further use of user namespaces inside sandbox and fail unless
// further use of user namespace inside sandbox is disabled if false
// (--disable-userns) (--assert-userns-disabled)
UserNS bool `json:"userns"`
// custom uid in the sandbox, requires new user namespace
// (--uid UID)
UID *int `json:"uid,omitempty"`
// custom gid in the sandbox, requires new user namespace
// (--gid GID)
GID *int `json:"gid,omitempty"`
// custom hostname in the sandbox, requires new uts namespace
// (--hostname NAME)
Hostname string `json:"hostname,omitempty"`
// change directory
// (--chdir DIR)
Chdir string `json:"chdir,omitempty"`
// unset all environment variables
// (--clearenv)
Clearenv bool `json:"clearenv"`
// set environment variable
// (--setenv VAR VALUE)
SetEnv map[string]string `json:"setenv,omitempty"`
// unset environment variables
// (--unsetenv VAR)
UnsetEnv []string `json:"unsetenv,omitempty"`
// take a lock on file while sandbox is running
// (--lock-file DEST)
LockFile []string `json:"lock_file,omitempty"`
// ordered filesystem args
Filesystem []FSBuilder
// change permissions (must already exist)
// (--chmod OCTAL PATH)
Chmod ChmodConfig `json:"chmod,omitempty"`
// create a new terminal session
// (--new-session)
NewSession bool `json:"new_session"`
// kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.
// (--die-with-parent)
DieWithParent bool `json:"die_with_parent"`
// do not install a reaper process with PID=1
// (--as-pid-1)
AsInit bool `json:"as_init"`
// keep this fd open while sandbox is running
// (--sync-fd FD)
sync *os.File
/* unmapped options include:
--unshare-user-try Create new user namespace if possible else continue by skipping it
--unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it
--userns FD Use this user namespace (cannot combine with --unshare-user)
--userns2 FD After setup switch to this user namespace, only useful with --userns
--pidns FD Use this pid namespace (as parent namespace if using --unshare-pid)
--exec-label LABEL Exec label for the sandbox
--file-label LABEL File label for temporary sandbox content
--file FD DEST Copy from FD to destination DEST
--bind-data FD DEST Copy from FD to file which is bind-mounted on DEST
--ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST
--seccomp FD Load and use seccomp rules from FD (not repeatable)
--add-seccomp-fd FD Load and use seccomp rules from FD (repeatable)
--block-fd FD Block on FD until some data to read is available
--userns-block-fd FD Block on FD until the user namespace is ready
--info-fd FD Write information about the running container to FD
--json-status-fd FD Write container status to FD as multiple JSON documents
--cap-add CAP Add cap CAP when running as privileged user
--cap-drop CAP Drop cap CAP when running as privileged user
among which --args is used internally for passing arguments */
}
// Sync keep this fd open while sandbox is running
// (--sync-fd FD)
func (c *Config) Sync() *os.File {
return c.sync
}
type UnshareConfig struct {
// (--unshare-user)
// create new user namespace
User bool `json:"user"`
// (--unshare-ipc)
// create new ipc namespace
IPC bool `json:"ipc"`
// (--unshare-pid)
// create new pid namespace
PID bool `json:"pid"`
// (--unshare-net)
// create new network namespace
Net bool `json:"net"`
// (--unshare-uts)
// create new uts namespace
UTS bool `json:"uts"`
// (--unshare-cgroup)
// create new cgroup namespace
CGroup bool `json:"cgroup"`
}
type PermConfig[T FSBuilder] struct {
// set permissions of next argument
// (--perms OCTAL)
Mode *os.FileMode `json:"mode,omitempty"`
// path to get the new permission
// (--bind-data, --file, etc.)
Inner T `json:"path"`
}
func (p *PermConfig[T]) Path() string {
return p.Inner.Path()
}
func (p *PermConfig[T]) Len() int {
if p.Mode != nil {
return p.Inner.Len() + 2
} else {
return p.Inner.Len()
}
}
func (p *PermConfig[T]) Append(args *[]string) {
if p.Mode != nil {
*args = append(*args, intArgs[Perms], strconv.FormatInt(int64(*p.Mode), 8))
}
p.Inner.Append(args)
}
type TmpfsConfig struct {
// set size of tmpfs
// (--size BYTES)
Size int `json:"size,omitempty"`
// mount point of new tmpfs
// (--tmpfs DEST)
Dir string `json:"dir"`
}
func (t *TmpfsConfig) Path() string {
return t.Dir
}
func (t *TmpfsConfig) Len() int {
if t.Size > 0 {
return 4
} else {
return 2
}
}
func (t *TmpfsConfig) Append(args *[]string) {
if t.Size > 0 {
*args = append(*args, intArgs[Size], strconv.Itoa(t.Size))
}
*args = append(*args, awkwardArgs[Tmpfs], t.Dir)
}
type SymlinkConfig [2]string
func (s SymlinkConfig) Path() string {
return s[1]
}
func (s SymlinkConfig) Len() int {
return 3
}
func (s SymlinkConfig) Append(args *[]string) {
*args = append(*args, awkwardArgs[Symlink], s[0], s[1])
}
type ChmodConfig map[string]os.FileMode
func (c ChmodConfig) Len() int {
return len(c)
}
func (c ChmodConfig) Append(args *[]string) {
for path, mode := range c {
*args = append(*args, pairArgs[Chmod], strconv.FormatInt(int64(mode), 8), path)
}
}

145
helper/bwrap/config.set.go Normal file
View File

@ -0,0 +1,145 @@
package bwrap
import "os"
/*
Bind binds mount src on host to dest in sandbox.
Bind(src, dest) bind mount host path readonly on sandbox
(--ro-bind SRC DEST).
Bind(src, dest, true) equal to ROBind but ignores non-existent host path
(--ro-bind-try SRC DEST).
Bind(src, dest, false, true) bind mount host path on sandbox.
(--bind SRC DEST).
Bind(src, dest, true, true) equal to Bind but ignores non-existent host path
(--bind-try SRC DEST).
Bind(src, dest, false, true, true) bind mount host path on sandbox, allowing device access
(--dev-bind SRC DEST).
Bind(src, dest, true, true, true) equal to DevBind but ignores non-existent host path
(--dev-bind-try SRC DEST).
*/
func (c *Config) Bind(src, dest string, opts ...bool) *Config {
var (
try bool
write bool
dev bool
)
if len(opts) > 0 {
try = opts[0]
}
if len(opts) > 1 {
write = opts[1]
}
if len(opts) > 2 {
dev = opts[2]
}
if dev {
if try {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[DevBindTry], src, dest})
} else {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[DevBind], src, dest})
}
return c
} else if write {
if try {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[BindTry], src, dest})
} else {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[Bind], src, dest})
}
return c
} else {
if try {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[ROBindTry], src, dest})
} else {
c.Filesystem = append(c.Filesystem, &pairF{pairArgs[ROBind], src, dest})
}
return c
}
}
// RemountRO remount path as readonly; does not recursively remount
// (--remount-ro DEST)
func (c *Config) RemountRO(dest string) *Config {
c.Filesystem = append(c.Filesystem, &stringF{stringArgs[RemountRO], dest})
return c
}
// Procfs mount new procfs in sandbox
// (--proc DEST)
func (c *Config) Procfs(dest string) *Config {
c.Filesystem = append(c.Filesystem, &stringF{stringArgs[Procfs], dest})
return c
}
// DevTmpfs mount new dev in sandbox
// (--dev DEST)
func (c *Config) DevTmpfs(dest string) *Config {
c.Filesystem = append(c.Filesystem, &stringF{stringArgs[DevTmpfs], dest})
return c
}
// Tmpfs mount new tmpfs in sandbox
// (--tmpfs DEST)
func (c *Config) Tmpfs(dest string, size int, perm ...os.FileMode) *Config {
tmpfs := &PermConfig[*TmpfsConfig]{Inner: &TmpfsConfig{Dir: dest}}
if size >= 0 {
tmpfs.Inner.Size = size
}
if len(perm) == 1 {
tmpfs.Mode = &perm[0]
}
c.Filesystem = append(c.Filesystem, tmpfs)
return c
}
// Mqueue mount new mqueue in sandbox
// (--mqueue DEST)
func (c *Config) Mqueue(dest string) *Config {
c.Filesystem = append(c.Filesystem, &stringF{stringArgs[Mqueue], dest})
return c
}
// Dir create dir in sandbox
// (--dir DEST)
func (c *Config) Dir(dest string) *Config {
c.Filesystem = append(c.Filesystem, &stringF{stringArgs[Dir], dest})
return c
}
// Symlink create symlink within sandbox
// (--symlink SRC DEST)
func (c *Config) Symlink(src, dest string, perm ...os.FileMode) *Config {
symlink := &PermConfig[SymlinkConfig]{Inner: SymlinkConfig{src, dest}}
if len(perm) == 1 {
symlink.Mode = &perm[0]
}
c.Filesystem = append(c.Filesystem, symlink)
return c
}
// SetUID sets custom uid in the sandbox, requires new user namespace (--uid UID).
func (c *Config) SetUID(uid int) *Config {
if uid >= 0 {
c.UID = &uid
}
return c
}
// SetGID sets custom gid in the sandbox, requires new user namespace (--gid GID).
func (c *Config) SetGID(gid int) *Config {
if gid >= 0 {
c.GID = &gid
}
return c
}
// SetSync sets the sync pipe kept open while sandbox is running
// (--sync-fd FD)
func (c *Config) SetSync(s *os.File) *Config {
c.sync = s
return c
}

223
helper/bwrap/config_test.go Normal file
View File

@ -0,0 +1,223 @@
package bwrap
import (
"slices"
"testing"
)
func TestConfig_Args(t *testing.T) {
testCases := []struct {
name string
conf *Config
want []string
}{
{
name: "xdg-dbus-proxy constraint sample",
conf: (&Config{
Unshare: nil,
UserNS: false,
Clearenv: true,
DieWithParent: true,
}).
Symlink("usr/bin", "/bin").
Symlink("var/home", "/home").
Symlink("usr/lib", "/lib").
Symlink("usr/lib64", "/lib64").
Symlink("run/media", "/media").
Symlink("var/mnt", "/mnt").
Symlink("var/opt", "/opt").
Symlink("sysroot/ostree", "/ostree").
Symlink("var/roothome", "/root").
Symlink("usr/sbin", "/sbin").
Symlink("var/srv", "/srv").
Bind("/run", "/run", false, true).
Bind("/tmp", "/tmp", false, true).
Bind("/var", "/var", false, true).
Bind("/run/user/1971/.dbus-proxy/", "/run/user/1971/.dbus-proxy/", false, true).
Bind("/boot", "/boot").
Bind("/dev", "/dev").
Bind("/proc", "/proc").
Bind("/sys", "/sys").
Bind("/sysroot", "/sysroot").
Bind("/usr", "/usr").
Bind("/etc", "/etc"),
want: []string{
"--unshare-all", "--unshare-user",
"--disable-userns", "--assert-userns-disabled",
"--clearenv", "--die-with-parent",
"--symlink", "usr/bin", "/bin",
"--symlink", "var/home", "/home",
"--symlink", "usr/lib", "/lib",
"--symlink", "usr/lib64", "/lib64",
"--symlink", "run/media", "/media",
"--symlink", "var/mnt", "/mnt",
"--symlink", "var/opt", "/opt",
"--symlink", "sysroot/ostree", "/ostree",
"--symlink", "var/roothome", "/root",
"--symlink", "usr/sbin", "/sbin",
"--symlink", "var/srv", "/srv",
"--bind", "/run", "/run",
"--bind", "/tmp", "/tmp",
"--bind", "/var", "/var",
"--bind", "/run/user/1971/.dbus-proxy/", "/run/user/1971/.dbus-proxy/",
"--ro-bind", "/boot", "/boot",
"--ro-bind", "/dev", "/dev",
"--ro-bind", "/proc", "/proc",
"--ro-bind", "/sys", "/sys",
"--ro-bind", "/sysroot", "/sysroot",
"--ro-bind", "/usr", "/usr",
"--ro-bind", "/etc", "/etc",
},
},
{
name: "fortify permissive default nixos",
conf: (&Config{
Unshare: nil,
Net: true,
UserNS: true,
Clearenv: true,
SetEnv: map[string]string{
"HOME": "/home/chronos",
"TERM": "xterm-256color",
"FORTIFY_INIT": "3",
"XDG_RUNTIME_DIR": "/run/user/150",
"XDG_SESSION_CLASS": "user",
"XDG_SESSION_TYPE": "tty",
"SHELL": "/run/current-system/sw/bin/zsh",
"USER": "chronos",
},
DieWithParent: true,
AsInit: true,
}).SetUID(65534).SetGID(65534).
Procfs("/proc").DevTmpfs("/dev").Mqueue("/dev/mqueue").
Bind("/bin", "/bin", false, true).
Bind("/boot", "/boot", false, true).
Bind("/etc", "/etc", false, true).
Bind("/home", "/home", false, true).
Bind("/lib", "/lib", false, true).
Bind("/lib64", "/lib64", false, true).
Bind("/nix", "/nix", false, true).
Bind("/root", "/root", false, true).
Bind("/srv", "/srv", false, true).
Bind("/sys", "/sys", false, true).
Bind("/usr", "/usr", false, true).
Bind("/var", "/var", false, true).
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
Bind("/run/binfmt", "/run/binfmt", false, true).
Bind("/run/booted-system", "/run/booted-system", false, true).
Bind("/run/credentials", "/run/credentials", false, true).
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
Bind("/run/current-system", "/run/current-system", false, true).
Bind("/run/host", "/run/host", false, true).
Bind("/run/keys", "/run/keys", false, true).
Bind("/run/libvirt", "/run/libvirt", false, true).
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
Bind("/run/lock", "/run/lock", false, true).
Bind("/run/log", "/run/log", false, true).
Bind("/run/lvm", "/run/lvm", false, true).
Bind("/run/mount", "/run/mount", false, true).
Bind("/run/nginx", "/run/nginx", false, true).
Bind("/run/nscd", "/run/nscd", false, true).
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
Bind("/run/pppd", "/run/pppd", false, true).
Bind("/run/resolvconf", "/run/resolvconf", false, true).
Bind("/run/sddm", "/run/sddm", false, true).
Bind("/run/syncoid", "/run/syncoid", false, true).
Bind("/run/systemd", "/run/systemd", false, true).
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
Bind("/run/udev", "/run/udev", false, true).
Bind("/run/udisks2", "/run/udisks2", false, true).
Bind("/run/utmp", "/run/utmp", false, true).
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
Bind("/run/wrappers", "/run/wrappers", false, true).
Bind("/run/zed.pid", "/run/zed.pid", false, true).
Bind("/run/zed.state", "/run/zed.state", false, true).
Bind("/tmp/fortify.1971/tmpdir/150", "/tmp", false, true).
Tmpfs("/tmp/fortify.1971", 1048576).
Tmpfs("/run/user", 1048576).
Tmpfs("/run/user/150", 8388608).
Bind("/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd").
Bind("/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group").
Bind("/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd", "/etc/passwd").
Bind("/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group", "/etc/group").
Tmpfs("/var/run/nscd", 8192),
want: []string{
"--unshare-all", "--unshare-user", "--share-net",
"--clearenv", "--die-with-parent", "--as-pid-1",
"--uid", "65534",
"--gid", "65534",
"--setenv", "FORTIFY_INIT", "3",
"--setenv", "HOME", "/home/chronos",
"--setenv", "SHELL", "/run/current-system/sw/bin/zsh",
"--setenv", "TERM", "xterm-256color",
"--setenv", "USER", "chronos",
"--setenv", "XDG_RUNTIME_DIR", "/run/user/150",
"--setenv", "XDG_SESSION_CLASS", "user",
"--setenv", "XDG_SESSION_TYPE", "tty",
"--proc", "/proc", "--dev", "/dev",
"--mqueue", "/dev/mqueue",
"--bind", "/bin", "/bin",
"--bind", "/boot", "/boot",
"--bind", "/etc", "/etc",
"--bind", "/home", "/home",
"--bind", "/lib", "/lib",
"--bind", "/lib64", "/lib64",
"--bind", "/nix", "/nix",
"--bind", "/root", "/root",
"--bind", "/srv", "/srv",
"--bind", "/sys", "/sys",
"--bind", "/usr", "/usr",
"--bind", "/var", "/var",
"--bind", "/run/NetworkManager", "/run/NetworkManager",
"--bind", "/run/agetty.reload", "/run/agetty.reload",
"--bind", "/run/binfmt", "/run/binfmt",
"--bind", "/run/booted-system", "/run/booted-system",
"--bind", "/run/credentials", "/run/credentials",
"--bind", "/run/cryptsetup", "/run/cryptsetup",
"--bind", "/run/current-system", "/run/current-system",
"--bind", "/run/host", "/run/host",
"--bind", "/run/keys", "/run/keys",
"--bind", "/run/libvirt", "/run/libvirt",
"--bind", "/run/libvirtd.pid", "/run/libvirtd.pid",
"--bind", "/run/lock", "/run/lock",
"--bind", "/run/log", "/run/log",
"--bind", "/run/lvm", "/run/lvm",
"--bind", "/run/mount", "/run/mount",
"--bind", "/run/nginx", "/run/nginx",
"--bind", "/run/nscd", "/run/nscd",
"--bind", "/run/opengl-driver", "/run/opengl-driver",
"--bind", "/run/pppd", "/run/pppd",
"--bind", "/run/resolvconf", "/run/resolvconf",
"--bind", "/run/sddm", "/run/sddm",
"--bind", "/run/syncoid", "/run/syncoid",
"--bind", "/run/systemd", "/run/systemd",
"--bind", "/run/tmpfiles.d", "/run/tmpfiles.d",
"--bind", "/run/udev", "/run/udev",
"--bind", "/run/udisks2", "/run/udisks2",
"--bind", "/run/utmp", "/run/utmp",
"--bind", "/run/virtlogd.pid", "/run/virtlogd.pid",
"--bind", "/run/wrappers", "/run/wrappers",
"--bind", "/run/zed.pid", "/run/zed.pid",
"--bind", "/run/zed.state", "/run/zed.state",
"--bind", "/tmp/fortify.1971/tmpdir/150", "/tmp",
"--size", "1048576", "--tmpfs", "/tmp/fortify.1971",
"--size", "1048576", "--tmpfs", "/run/user",
"--size", "8388608", "--tmpfs", "/run/user/150",
"--ro-bind", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd",
"--ro-bind", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group",
"--ro-bind", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/passwd", "/etc/passwd",
"--ro-bind", "/tmp/fortify.1971/67a97cc824a64ef789f16b20ca6ce311/group", "/etc/group",
"--size", "8192", "--tmpfs", "/var/run/nscd",
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if got := tc.conf.Args(); !slices.Equal(got, tc.want) {
t.Errorf("Args() = %#v, want %#v", got, tc.want)
}
})
}
}

112
helper/bwrap_test.go Normal file
View File

@ -0,0 +1,112 @@
package helper_test
import (
"errors"
"fmt"
"os"
"strings"
"testing"
"git.gensokyo.uk/security/fortify/helper"
"git.gensokyo.uk/security/fortify/helper/bwrap"
)
func TestBwrap(t *testing.T) {
sc := &bwrap.Config{
Unshare: nil,
Net: true,
UserNS: false,
Hostname: "localhost",
Chdir: "/nonexistent",
Clearenv: true,
NewSession: true,
DieWithParent: true,
AsInit: true,
}
t.Run("nonexistent bwrap name", func(t *testing.T) {
bubblewrapName := helper.BubblewrapName
helper.BubblewrapName = "/nonexistent"
t.Cleanup(func() {
helper.BubblewrapName = bubblewrapName
})
h := helper.MustNewBwrap(sc, argsWt, "fortify", argF)
if err := h.Start(); !errors.Is(err, os.ErrNotExist) {
t.Errorf("Start() error = %v, wantErr %v",
err, os.ErrNotExist)
}
})
t.Run("valid new helper nil check", func(t *testing.T) {
if got := helper.MustNewBwrap(sc, argsWt, "fortify", argF); got == nil {
t.Errorf("MustNewBwrap(%#v, %#v, %#v) got nil",
sc, argsWt, "fortify")
return
}
})
t.Run("invalid bwrap config new helper panic", func(t *testing.T) {
defer func() {
wantPanic := "argument contains null character"
if r := recover(); r != wantPanic {
t.Errorf("MustNewBwrap: panic = %q, want %q",
r, wantPanic)
}
}()
helper.MustNewBwrap(&bwrap.Config{Hostname: "\x00"}, nil, "fortify", argF)
})
t.Run("start notify without pipes panic", func(t *testing.T) {
defer func() {
wantPanic := "attempted to start with status monitoring on a bwrap child initialised without pipes"
if r := recover(); r != wantPanic {
t.Errorf("StartNotify: panic = %q, want %q",
r, wantPanic)
}
}()
panic(fmt.Sprintf("unreachable: %v",
helper.MustNewBwrap(sc, nil, "fortify", argF).StartNotify(make(chan error))))
})
t.Run("start without pipes", func(t *testing.T) {
helper.InternalReplaceExecCommand(t)
h := helper.MustNewBwrap(sc, nil, "crash-test-dummy", argFChecked)
cmd := h.Unwrap()
stdout, stderr := new(strings.Builder), new(strings.Builder)
cmd.Stdout, cmd.Stderr = stdout, stderr
t.Run("close without pipes panic", func(t *testing.T) {
defer func() {
wantPanic := "attempted to close bwrap child initialised without pipes"
if r := recover(); r != wantPanic {
t.Errorf("Close: panic = %q, want %q",
r, wantPanic)
}
}()
panic(fmt.Sprintf("unreachable: %v",
h.Close()))
})
if err := h.Start(); err != nil {
t.Errorf("Start() error = %v",
err)
return
}
if err := h.Wait(); err != nil {
t.Errorf("Wait() err = %v stderr = %s",
err, stderr)
}
})
t.Run("implementation compliance", func(t *testing.T) {
testHelper(t, func() helper.Helper { return helper.MustNewBwrap(sc, argsWt, "crash-test-dummy", argF) })
})
}

93
helper/direct.go Normal file
View File

@ -0,0 +1,93 @@
package helper
import (
"errors"
"io"
"os/exec"
"sync"
)
// direct wraps *exec.Cmd and manages status and args fd.
// Args is always 3 and status if set is always 4.
type direct struct {
// helper pipes
// cannot be nil
p *pipes
// returns an array of arguments passed directly
// to the helper process
argF func(argsFD, statFD int) []string
lock sync.RWMutex
*exec.Cmd
}
func (h *direct) StartNotify(ready chan error) error {
h.lock.Lock()
defer h.lock.Unlock()
// Check for doubled Start calls before we defer failure cleanup. If the prior
// call to Start succeeded, we don't want to spuriously close its pipes.
if h.Cmd.Process != nil {
return errors.New("exec: already started")
}
h.p.ready = ready
if argsFD, statFD, err := h.p.prepareCmd(h.Cmd); err != nil {
return err
} else {
h.Cmd.Args = append(h.Cmd.Args, h.argF(argsFD, statFD)...)
}
if ready != nil {
h.Cmd.Env = append(h.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=1")
} else {
h.Cmd.Env = append(h.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=0")
}
if err := h.Cmd.Start(); err != nil {
return err
}
if err := h.p.readyWriteArgs(); err != nil {
return err
}
return nil
}
func (h *direct) Wait() error {
h.lock.RLock()
defer h.lock.RUnlock()
if h.Cmd.Process == nil {
return errors.New("exec: not started")
}
defer h.p.mustClosePipes()
if h.Cmd.ProcessState != nil {
return errors.New("exec: Wait was already called")
}
return h.Cmd.Wait()
}
func (h *direct) Close() error {
return h.p.closeStatus()
}
func (h *direct) Start() error {
return h.StartNotify(nil)
}
func (h *direct) Unwrap() *exec.Cmd {
return h.Cmd
}
// New initialises a new direct Helper instance with wt as the null-terminated argument writer.
// Function argF returns an array of arguments passed directly to the child process.
func New(wt io.WriterTo, name string, argF func(argsFD, statFD int) []string) Helper {
if wt == nil {
panic("attempted to create helper with invalid argument writer")
}
return &direct{p: &pipes{args: wt}, argF: argF, Cmd: execCommand(name)}
}

44
helper/direct_test.go Normal file
View File

@ -0,0 +1,44 @@
package helper_test
import (
"errors"
"os"
"testing"
"git.gensokyo.uk/security/fortify/helper"
)
func TestDirect(t *testing.T) {
t.Run("start non-existent helper path", func(t *testing.T) {
h := helper.New(argsWt, "/nonexistent", argF)
if err := h.Start(); !errors.Is(err, os.ErrNotExist) {
t.Errorf("Start() error = %v, wantErr %v",
err, os.ErrNotExist)
}
})
t.Run("valid new helper nil check", func(t *testing.T) {
if got := helper.New(argsWt, "fortify", argF); got == nil {
t.Errorf("New(%q, %q) got nil",
argsWt, "fortify")
return
}
})
t.Run("invalid new helper panic", func(t *testing.T) {
defer func() {
wantPanic := "attempted to create helper with invalid argument writer"
if r := recover(); r != wantPanic {
t.Errorf("New: panic = %q, want %q",
r, wantPanic)
}
}()
helper.New(nil, "fortify", argF)
})
t.Run("implementation compliance", func(t *testing.T) {
testHelper(t, func() helper.Helper { return helper.New(argsWt, "crash-test-dummy", argF) })
})
}

36
helper/helper.go Normal file
View File

@ -0,0 +1,36 @@
// Package helper runs external helpers with optional sandboxing and manages their status/args pipes.
package helper
import (
"errors"
"os/exec"
)
var (
ErrStatusFault = errors.New("generic status pipe fault")
ErrStatusRead = errors.New("unexpected status response")
)
const (
// FortifyHelper is set for the process launched by Helper.
FortifyHelper = "FORTIFY_HELPER"
// FortifyStatus is 1 when sync fd is enabled and 0 otherwise.
FortifyStatus = "FORTIFY_STATUS"
)
type Helper interface {
// StartNotify starts the helper process.
// A status pipe is passed to the helper if ready is not nil.
StartNotify(ready chan error) error
// Start starts the helper process.
Start() error
// Close closes the status pipe.
// If helper is started without the status pipe, Close panics.
Close() error
// Wait calls wait on the child process and cleans up pipes.
Wait() error
// Unwrap returns the underlying exec.Cmd instance.
Unwrap() *exec.Cmd
}
var execCommand = exec.Command

167
helper/helper_test.go Normal file
View File

@ -0,0 +1,167 @@
package helper_test
import (
"strconv"
"strings"
"testing"
"time"
"git.gensokyo.uk/security/fortify/helper"
)
var (
wantArgs = []string{
"unix:path=/run/dbus/system_bus_socket",
"/tmp/fortify.1971/12622d846cc3fe7b4c10359d01f0eb47/system_bus_socket",
"--filter",
"--talk=org.bluez",
"--talk=org.freedesktop.Avahi",
"--talk=org.freedesktop.UPower",
}
wantPayload = strings.Join(wantArgs, "\x00") + "\x00"
argsWt = helper.MustNewCheckedArgs(wantArgs)
)
func argF(argsFD, statFD int) []string {
if argsFD == -1 {
panic("invalid args fd")
}
return argFChecked(argsFD, statFD)
}
func argFChecked(argsFD, statFD int) []string {
if statFD == -1 {
return []string{"--args", strconv.Itoa(argsFD)}
} else {
return []string{"--args", strconv.Itoa(argsFD), "--fd", strconv.Itoa(statFD)}
}
}
// this function tests an implementation of the helper.Helper interface
func testHelper(t *testing.T, createHelper func() helper.Helper) {
helper.InternalReplaceExecCommand(t)
t.Run("start helper with status channel and wait", func(t *testing.T) {
h := createHelper()
ready := make(chan error, 1)
cmd := h.Unwrap()
stdout, stderr := new(strings.Builder), new(strings.Builder)
cmd.Stdout, cmd.Stderr = stdout, stderr
t.Run("wait not yet started helper", func(t *testing.T) {
wantErr := "exec: not started"
if err := h.Wait(); err != nil && err.Error() != wantErr {
t.Errorf("Wait(%v) error = %v, wantErr %v",
ready,
err, wantErr)
return
}
})
t.Log("starting helper stub")
if err := h.StartNotify(ready); err != nil {
t.Errorf("StartNotify(%v) error = %v",
ready,
err)
return
}
t.Run("start already started helper", func(t *testing.T) {
wantErr := "exec: already started"
if err := h.StartNotify(ready); err != nil && err.Error() != wantErr {
t.Errorf("StartNotify(%v) error = %v, wantErr %v",
ready,
err, wantErr)
return
}
})
t.Log("waiting on status channel with timeout")
select {
case <-time.NewTimer(5 * time.Second).C:
t.Errorf("never got a ready response")
t.Errorf("stdout:\n%s", stdout.String())
t.Errorf("stderr:\n%s", stderr.String())
if err := cmd.Process.Kill(); err != nil {
panic(err.Error())
}
return
case err := <-ready:
if err != nil {
t.Errorf("StartNotify(%v) latent error = %v",
ready,
err)
}
}
t.Log("closing status pipe")
if err := h.Close(); err != nil {
t.Errorf("Close() error = %v",
err)
}
t.Log("waiting on helper")
if err := h.Wait(); err != nil {
t.Errorf("Wait() err = %v stderr = %s",
err, stderr)
}
t.Run("wait already finalised helper", func(t *testing.T) {
wantErr := "exec: Wait was already called"
if err := h.Wait(); err != nil && err.Error() != wantErr {
t.Errorf("Wait(%v) error = %v, wantErr %v",
ready,
err, wantErr)
return
}
})
if got := stdout.String(); !strings.HasPrefix(got, wantPayload) {
t.Errorf("StartNotify(%v) stdout = %v, want %v",
ready,
got, wantPayload)
}
})
t.Run("start helper and wait", func(t *testing.T) {
h := createHelper()
cmd := h.Unwrap()
stdout, stderr := new(strings.Builder), new(strings.Builder)
cmd.Stdout, cmd.Stderr = stdout, stderr
if err := h.Start(); err != nil {
t.Errorf("Start() error = %v",
err)
return
}
t.Run("close helper without status pipe", func(t *testing.T) {
defer func() {
wantPanic := "attempted to close helper with no status pipe"
if r := recover(); r != wantPanic {
t.Errorf("Close() panic = %v, wantPanic %v",
r, wantPanic)
}
}()
if err := h.Close(); err != nil {
t.Errorf("Close() error = %v",
err)
return
}
})
if err := h.Wait(); err != nil {
t.Errorf("Wait() err = %v stderr = %s",
err, stderr)
}
if got := stdout.String(); !strings.HasPrefix(got, wantPayload) {
t.Errorf("Start() stdout = %v, want %v",
got, wantPayload)
}
})
}

149
helper/pipe.go Normal file
View File

@ -0,0 +1,149 @@
package helper
import (
"errors"
"io"
"os"
"os/exec"
"git.gensokyo.uk/security/fortify/internal/proc"
)
type pipes struct {
args io.WriterTo
statP [2]*os.File
argsP [2]*os.File
ready chan error
cmd *exec.Cmd
}
func (p *pipes) pipe() error {
if p.statP[0] != nil || p.statP[1] != nil ||
p.argsP[0] != nil || p.argsP[1] != nil {
panic("attempted to pipe twice")
}
if p.args == nil {
panic("attempted to pipe without args")
}
// create pipes
if pr, pw, err := os.Pipe(); err != nil {
return err
} else {
p.argsP[0], p.argsP[1] = pr, pw
}
// create status pipes if ready signal is requested
if p.ready != nil {
if pr, pw, err := os.Pipe(); err != nil {
return err
} else {
p.statP[0], p.statP[1] = pr, pw
}
}
return nil
}
// calls pipe to create pipes and sets them up as ExtraFiles, returning their fd
func (p *pipes) prepareCmd(cmd *exec.Cmd) (argsFd, statFd int, err error) {
argsFd, statFd = -1, -1
if err = p.pipe(); err != nil {
return
}
// save a reference of cmd for future use
p.cmd = cmd
argsFd = int(proc.ExtraFile(cmd, p.argsP[0]))
if p.ready != nil {
statFd = int(proc.ExtraFile(cmd, p.statP[1]))
}
return
}
func (p *pipes) readyWriteArgs() error {
statsP, argsP := p.statP[0], p.argsP[1]
// write arguments and close args pipe
if _, err := p.args.WriteTo(argsP); err != nil {
if err1 := p.cmd.Process.Kill(); err1 != nil {
// should be unreachable
panic(err1.Error())
}
return err
} else {
if err = argsP.Close(); err != nil {
if err1 := p.cmd.Process.Kill(); err1 != nil {
// should be unreachable
panic(err1.Error())
}
return err
}
}
if p.ready != nil {
// monitor stat pipe
go func() {
n, err := statsP.Read(make([]byte, 1))
switch n {
case -1:
if err1 := p.cmd.Process.Kill(); err1 != nil {
// should be unreachable
panic(err1.Error())
}
// ensure error is not nil
if err == nil {
err = ErrStatusFault
}
p.ready <- err
case 0:
// ensure error is not nil
if err == nil {
err = ErrStatusRead
}
p.ready <- err
case 1:
p.ready <- nil
default:
panic("unreachable") // unexpected read count
}
}()
}
return nil
}
func (p *pipes) mustClosePipes() {
if err := p.argsP[0].Close(); err != nil && !errors.Is(err, os.ErrClosed) {
// unreachable
panic(err.Error())
}
if err := p.argsP[1].Close(); err != nil && !errors.Is(err, os.ErrClosed) {
// unreachable
panic(err.Error())
}
if p.ready != nil {
if err := p.statP[0].Close(); err != nil && !errors.Is(err, os.ErrClosed) {
// unreachable
panic(err.Error())
}
if err := p.statP[1].Close(); err != nil && !errors.Is(err, os.ErrClosed) {
// unreachable
panic(err.Error())
}
}
}
func (p *pipes) closeStatus() error {
if p.ready == nil {
panic("attempted to close helper with no status pipe")
}
return p.statP[0].Close()
}

42
helper/pipe_test.go Normal file
View File

@ -0,0 +1,42 @@
package helper
import (
"testing"
)
func Test_pipes_pipe_mustClosePipes(t *testing.T) {
p := new(pipes)
t.Run("pipe without args", func(t *testing.T) {
defer func() {
wantPanic := "attempted to pipe without args"
if r := recover(); r != wantPanic {
t.Errorf("pipe() panic = %v, wantPanic %v",
r, wantPanic)
}
}()
_ = p.pipe()
})
p.args = MustNewCheckedArgs(make([]string, 0))
t.Run("obtain pipes", func(t *testing.T) {
if err := p.pipe(); err != nil {
t.Errorf("pipe() error = %v",
err)
return
}
})
t.Run("pipe twice", func(t *testing.T) {
defer func() {
wantPanic := "attempted to pipe twice"
if r := recover(); r != wantPanic {
t.Errorf("pipe() panic = %v, wantPanic %v",
r, wantPanic)
}
}()
_ = p.pipe()
})
p.mustClosePipes()
}

175
helper/stub.go Normal file
View File

@ -0,0 +1,175 @@
package helper
import (
"flag"
"io"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"testing"
"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;
// it is part of the implementation of the helper stub.
func InternalChildStub() {
// this test mocks the helper process
if os.Getenv(FortifyHelper) != "1" ||
os.Getenv(FortifyStatus) == "-1" { // this indicates the stub is being invoked as a bwrap child without pipes
return
}
argsFD := flag.Int("args", -1, "")
statFD := flag.Int("fd", -1, "")
_ = flag.CommandLine.Parse(os.Args[4:])
switch os.Args[3] {
case "bwrap":
bwrapStub(argsFD, statFD)
default:
genericStub(argsFD, statFD)
}
fmsg.Exit(0)
}
// InternalReplaceExecCommand is an internal function but exported because it is cross-package;
// it is part of the implementation of the helper stub.
func InternalReplaceExecCommand(t *testing.T) {
t.Cleanup(func() {
execCommand = exec.Command
})
// replace execCommand to have the resulting *exec.Cmd launch TestHelperChildStub
execCommand = func(name string, arg ...string) *exec.Cmd {
// pass through nonexistent path
if name == "/nonexistent" && len(arg) == 0 {
return exec.Command(name)
}
return exec.Command(os.Args[0], append([]string{"-test.run=TestHelperChildStub", "--", name}, arg...)...)
}
}
func genericStub(argsFD, statFD *int) {
// simulate args pipe behaviour
func() {
if *argsFD == -1 {
panic("attempted to start helper without passing args pipe fd")
}
f := os.NewFile(uintptr(*argsFD), "|0")
if f == nil {
panic("attempted to start helper without args pipe")
}
if _, err := io.Copy(os.Stdout, f); err != nil {
panic("cannot read args: " + err.Error())
}
}()
var wait chan struct{}
// simulate status pipe behaviour
if os.Getenv(FortifyStatus) == "1" {
if *statFD == -1 {
panic("attempted to start helper with status reporting without passing status pipe fd")
}
wait = make(chan struct{})
go func() {
f := os.NewFile(uintptr(*statFD), "|1")
if f == nil {
panic("attempted to start with status reporting without status pipe")
}
if _, err := f.Write([]byte{'x'}); err != nil {
panic("cannot write to status pipe: " + err.Error())
}
// wait for status pipe close
var epoll int
if fd, err := syscall.EpollCreate1(0); err != nil {
panic("cannot open epoll fd: " + err.Error())
} else {
defer func() {
if err = syscall.Close(fd); err != nil {
panic("cannot close epoll fd: " + err.Error())
}
}()
epoll = fd
}
if err := syscall.EpollCtl(epoll, syscall.EPOLL_CTL_ADD, int(f.Fd()), &syscall.EpollEvent{}); err != nil {
panic("cannot add status pipe to epoll: " + err.Error())
}
events := make([]syscall.EpollEvent, 1)
if _, err := syscall.EpollWait(epoll, events, -1); err != nil {
panic("cannot poll status pipe: " + err.Error())
}
if events[0].Events != syscall.EPOLLERR {
panic(strconv.Itoa(int(events[0].Events)))
}
close(wait)
}()
}
if wait != nil {
<-wait
}
}
func bwrapStub(argsFD, statFD *int) {
// the bwrap launcher does not ever launch with sync fd
if *statFD != -1 {
panic("attempted to launch bwrap with status monitoring")
}
// test args pipe behaviour
func() {
if *argsFD == -1 {
panic("attempted to start bwrap without passing args pipe fd")
}
f := os.NewFile(uintptr(*argsFD), "|0")
if f == nil {
panic("attempted to start helper without args pipe")
}
got, want := new(strings.Builder), new(strings.Builder)
if _, err := io.Copy(got, f); err != nil {
panic("cannot read args: " + err.Error())
}
// hardcoded bwrap configuration used by test
if _, err := MustNewCheckedArgs((&bwrap.Config{
Unshare: nil,
Net: true,
UserNS: false,
Hostname: "localhost",
Chdir: "/nonexistent",
Clearenv: true,
NewSession: true,
DieWithParent: true,
AsInit: true,
}).Args()).WriteTo(want); err != nil {
panic("cannot read want: " + err.Error())
}
if len(flag.CommandLine.Args()) > 0 && flag.CommandLine.Args()[0] == "crash-test-dummy" && got.String() != want.String() {
panic("bad bwrap args\ngot: " + got.String() + "\nwant: " + want.String())
}
}()
if err := syscall.Exec(
os.Args[0],
append([]string{os.Args[0], "-test.run=TestHelperChildStub", "--"}, flag.CommandLine.Args()...),
os.Environ()); err != nil {
panic("cannot start general stub: " + err.Error())
}
}

11
helper/stub_test.go Normal file
View File

@ -0,0 +1,11 @@
package helper_test
import (
"testing"
"git.gensokyo.uk/security/fortify/helper"
)
func TestHelperChildStub(t *testing.T) {
helper.InternalChildStub()
}

97
internal/app/app.go Normal file
View File

@ -0,0 +1,97 @@
package app
import (
"sync"
"sync/atomic"
"git.gensokyo.uk/security/fortify/cmd/fshim/ipc/shim"
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/internal/linux"
)
type App interface {
// ID returns a copy of App's unique 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.
Wait() (int, error)
// WaitErr returns error returned by the underlying wait syscall.
WaitErr() error
Seal(config *fst.Config) error
String() string
}
type app struct {
// single-use config reference
ct *appCt
// application unique identifier
id *fst.ID
// operating system interface
os linux.System
// shim process manager
shim *shim.Shim
// child process related information
seal *appSeal
// error returned waiting for process
waitErr error
lock sync.RWMutex
}
func (a *app) ID() fst.ID {
return *a.id
}
func (a *app) String() string {
if a == nil {
return "(invalid fortified app)"
}
a.lock.RLock()
defer a.lock.RUnlock()
if a.shim != nil {
return a.shim.String()
}
if a.seal != nil {
return "(sealed fortified app as uid " + a.seal.sys.user.us + ")"
}
return "(unsealed fortified app)"
}
func (a *app) WaitErr() error {
return a.waitErr
}
func New(os linux.System) (App, error) {
a := new(app)
a.id = new(fst.ID)
a.os = os
return a, fst.NewAppID(a.id)
}
// appCt ensures its wrapped val is only accessed once
type appCt struct {
val *fst.Config
done *atomic.Bool
}
func (a *appCt) Unwrap() *fst.Config {
if !a.done.Load() {
defer a.done.Store(true)
return a.val
}
panic("attempted to access config reference twice")
}
func newAppCt(config *fst.Config) (ct *appCt) {
ct = new(appCt)
ct.done = new(atomic.Bool)
ct.val = config
return ct
}

View File

@ -0,0 +1,225 @@
package app_test
import (
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/system"
)
var testCasesNixos = []sealTestCase{
{
"nixos chromium direct wayland", new(stubNixOS),
&fst.Config{
ID: "org.chromium.Chromium",
Command: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"},
Confinement: fst.ConfinementConfig{
AppID: 1, Groups: []string{}, Username: "u0_a1",
Outer: "/var/lib/persist/module/fortify/0/1",
Sandbox: &fst.SandboxConfig{
UserNS: true, Net: true, MapRealUID: true, DirectWayland: true, Env: nil,
Filesystem: []*fst.FilesystemConfig{
{Src: "/bin", Must: true}, {Src: "/usr/bin", Must: true},
{Src: "/nix/store", Must: true}, {Src: "/run/current-system", Must: true},
{Src: "/sys/block"}, {Src: "/sys/bus"}, {Src: "/sys/class"}, {Src: "/sys/dev"}, {Src: "/sys/devices"},
{Src: "/run/opengl-driver", Must: true}, {Src: "/dev/dri", Device: true},
}, AutoEtc: true,
Override: []string{"/var/run/nscd"},
},
SystemBus: &dbus.Config{
Talk: []string{"org.bluez", "org.freedesktop.Avahi", "org.freedesktop.UPower"},
Filter: true,
},
SessionBus: &dbus.Config{
Talk: []string{
"org.freedesktop.FileManager1", "org.freedesktop.Notifications",
"org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
"org.kde.kwalletd5", "org.kde.kwalletd6",
},
Own: []string{
"org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*",
},
Call: map[string]string{}, Broadcast: map[string]string{},
Filter: true,
},
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
},
},
fst.ID{
0x8e, 0x2c, 0x76, 0xb0,
0x66, 0xda, 0xbe, 0x57,
0x4c, 0xf0, 0x73, 0xbd,
0xb4, 0x6e, 0xb5, 0xc1,
},
system.New(1000001).
Ensure("/tmp/fortify.1971", 0711).
Ephemeral(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1", 0711).
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
Ensure("/tmp/fortify.1971/tmpdir/1", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/1", acl.Read, acl.Write, acl.Execute).
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
Ephemeral(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", acl.Execute).
WriteType(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/passwd", "u0_a1:x:1971:1971:Fortify:/var/lib/persist/module/fortify/0/1:/run/current-system/sw/bin/zsh\n").
WriteType(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/group", "fortify:x:1971:\n").
Link("/run/user/1971/wayland-0", "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/wayland").
UpdatePermType(system.EWayland, "/run/user/1971/wayland-0", acl.Read, acl.Write, acl.Execute).
Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse").
CopyFile("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie", "/home/ophestra/xdg/config/pulse/cookie").
MustProxyDBus("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", &dbus.Config{
Talk: []string{
"org.freedesktop.FileManager1", "org.freedesktop.Notifications",
"org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
"org.kde.kwalletd5", "org.kde.kwalletd6",
},
Own: []string{
"org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*",
},
Call: map[string]string{}, Broadcast: map[string]string{},
Filter: true,
}, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", &dbus.Config{
Talk: []string{
"org.bluez",
"org.freedesktop.Avahi",
"org.freedesktop.UPower",
},
Filter: true,
}).
UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", acl.Read, acl.Write).
UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", acl.Read, acl.Write),
(&bwrap.Config{
Net: true,
UserNS: true,
Chdir: "/var/lib/persist/module/fortify/0/1",
Clearenv: true,
SetEnv: map[string]string{
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1971/bus",
"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/run/dbus/system_bus_socket",
"HOME": "/var/lib/persist/module/fortify/0/1",
"PULSE_COOKIE": "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie",
"PULSE_SERVER": "unix:/run/user/1971/pulse/native",
"SHELL": "/run/current-system/sw/bin/zsh",
"TERM": "xterm-256color",
"USER": "u0_a1",
"WAYLAND_DISPLAY": "/run/user/1971/wayland-0",
"XDG_RUNTIME_DIR": "/run/user/1971",
"XDG_SESSION_CLASS": "user",
"XDG_SESSION_TYPE": "tty",
},
Chmod: make(bwrap.ChmodConfig),
NewSession: true,
DieWithParent: true,
AsInit: true,
}).SetUID(1971).SetGID(1971).
Procfs("/proc").
Tmpfs("/fortify", 4096).
DevTmpfs("/dev").Mqueue("/dev/mqueue").
Bind("/bin", "/bin").
Bind("/usr/bin", "/usr/bin").
Bind("/nix/store", "/nix/store").
Bind("/run/current-system", "/run/current-system").
Bind("/sys/block", "/sys/block", true).
Bind("/sys/bus", "/sys/bus", true).
Bind("/sys/class", "/sys/class", true).
Bind("/sys/dev", "/sys/dev", true).
Bind("/sys/devices", "/sys/devices", true).
Bind("/run/opengl-driver", "/run/opengl-driver").
Bind("/dev/dri", "/dev/dri", true, true, true).
Bind("/etc", "/fortify/etc").
Symlink("/fortify/etc/alsa", "/etc/alsa").
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
Symlink("/fortify/etc/default", "/etc/default").
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
Symlink("/fortify/etc/fonts", "/etc/fonts").
Symlink("/fortify/etc/fstab", "/etc/fstab").
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
Symlink("/fortify/etc/hostid", "/etc/hostid").
Symlink("/fortify/etc/hostname", "/etc/hostname").
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
Symlink("/fortify/etc/hosts", "/etc/hosts").
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
Symlink("/fortify/etc/issue", "/etc/issue").
Symlink("/fortify/etc/kbd", "/etc/kbd").
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
Symlink("/fortify/etc/localtime", "/etc/localtime").
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
Symlink("/fortify/etc/lvm", "/etc/lvm").
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
Symlink("/proc/mounts", "/etc/mtab").
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
Symlink("/fortify/etc/nix", "/etc/nix").
Symlink("/fortify/etc/nixos", "/etc/nixos").
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
Symlink("/fortify/etc/os-release", "/etc/os-release").
Symlink("/fortify/etc/pam", "/etc/pam").
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
Symlink("/fortify/etc/pki", "/etc/pki").
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
Symlink("/fortify/etc/profile", "/etc/profile").
Symlink("/fortify/etc/protocols", "/etc/protocols").
Symlink("/fortify/etc/qemu", "/etc/qemu").
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
Symlink("/fortify/etc/rpc", "/etc/rpc").
Symlink("/fortify/etc/samba", "/etc/samba").
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
Symlink("/fortify/etc/services", "/etc/services").
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
Symlink("/fortify/etc/shadow", "/etc/shadow").
Symlink("/fortify/etc/shells", "/etc/shells").
Symlink("/fortify/etc/ssh", "/etc/ssh").
Symlink("/fortify/etc/ssl", "/etc/ssl").
Symlink("/fortify/etc/static", "/etc/static").
Symlink("/fortify/etc/subgid", "/etc/subgid").
Symlink("/fortify/etc/subuid", "/etc/subuid").
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
Symlink("/fortify/etc/systemd", "/etc/systemd").
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
Symlink("/fortify/etc/udev", "/etc/udev").
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
Symlink("/fortify/etc/UPower", "/etc/UPower").
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
Symlink("/fortify/etc/X11", "/etc/X11").
Symlink("/fortify/etc/zfs", "/etc/zfs").
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
Bind("/tmp/fortify.1971/tmpdir/1", "/tmp", false, true).
Tmpfs("/tmp/fortify.1971", 1048576).
Tmpfs("/run/user", 1048576).
Tmpfs("/run/user/1971", 8388608).
Bind("/var/lib/persist/module/fortify/0/1", "/var/lib/persist/module/fortify/0/1", false, true).
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/passwd", "/etc/passwd").
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/group", "/etc/group").
Bind("/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/wayland", "/run/user/1971/wayland-0").
Bind("/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse", "/run/user/1971/pulse/native").
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie", "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie").
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", "/run/user/1971/bus").
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", "/run/dbus/system_bus_socket").
Tmpfs("/var/run/nscd", 8192),
},
}

452
internal/app/app_pd_test.go Normal file
View File

@ -0,0 +1,452 @@
package app_test
import (
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/system"
)
var testCasesPd = []sealTestCase{
{
"nixos permissive defaults no enablements", new(stubNixOS),
&fst.Config{
Command: make([]string, 0),
Confinement: fst.ConfinementConfig{
AppID: 0,
Username: "chronos",
Outer: "/home/chronos",
},
},
fst.ID{
0x4a, 0x45, 0x0b, 0x65,
0x96, 0xd7, 0xbc, 0x15,
0xbd, 0x01, 0x78, 0x0e,
0xb9, 0xa6, 0x07, 0xac,
},
system.New(1000000).
Ensure("/tmp/fortify.1971", 0711).
Ephemeral(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac", 0711).
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
Ensure("/tmp/fortify.1971/tmpdir/0", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/0", acl.Read, acl.Write, acl.Execute).
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
Ephemeral(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", acl.Execute).
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n").
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "fortify:x:65534:\n"),
(&bwrap.Config{
Net: true,
UserNS: true,
Clearenv: true,
Chdir: "/home/chronos",
SetEnv: map[string]string{
"HOME": "/home/chronos",
"SHELL": "/run/current-system/sw/bin/zsh",
"TERM": "xterm-256color",
"USER": "chronos",
"XDG_RUNTIME_DIR": "/run/user/65534",
"XDG_SESSION_CLASS": "user",
"XDG_SESSION_TYPE": "tty"},
Chmod: make(bwrap.ChmodConfig),
DieWithParent: true,
AsInit: true,
}).SetUID(65534).SetGID(65534).
Procfs("/proc").
Tmpfs("/fortify", 4096).
DevTmpfs("/dev").Mqueue("/dev/mqueue").
Bind("/bin", "/bin", false, true).
Bind("/boot", "/boot", false, true).
Bind("/home", "/home", false, true).
Bind("/lib", "/lib", false, true).
Bind("/lib64", "/lib64", false, true).
Bind("/nix", "/nix", false, true).
Bind("/root", "/root", false, true).
Bind("/srv", "/srv", false, true).
Bind("/sys", "/sys", false, true).
Bind("/usr", "/usr", false, true).
Bind("/var", "/var", false, true).
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
Bind("/run/binfmt", "/run/binfmt", false, true).
Bind("/run/booted-system", "/run/booted-system", false, true).
Bind("/run/credentials", "/run/credentials", false, true).
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
Bind("/run/current-system", "/run/current-system", false, true).
Bind("/run/host", "/run/host", false, true).
Bind("/run/keys", "/run/keys", false, true).
Bind("/run/libvirt", "/run/libvirt", false, true).
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
Bind("/run/lock", "/run/lock", false, true).
Bind("/run/log", "/run/log", false, true).
Bind("/run/lvm", "/run/lvm", false, true).
Bind("/run/mount", "/run/mount", false, true).
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
Bind("/run/nginx", "/run/nginx", false, true).
Bind("/run/nixos", "/run/nixos", false, true).
Bind("/run/nscd", "/run/nscd", false, true).
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
Bind("/run/pppd", "/run/pppd", false, true).
Bind("/run/resolvconf", "/run/resolvconf", false, true).
Bind("/run/sddm", "/run/sddm", false, true).
Bind("/run/store", "/run/store", false, true).
Bind("/run/syncoid", "/run/syncoid", false, true).
Bind("/run/system", "/run/system", false, true).
Bind("/run/systemd", "/run/systemd", false, true).
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
Bind("/run/udev", "/run/udev", false, true).
Bind("/run/udisks2", "/run/udisks2", false, true).
Bind("/run/utmp", "/run/utmp", false, true).
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
Bind("/run/wrappers", "/run/wrappers", false, true).
Bind("/run/zed.pid", "/run/zed.pid", false, true).
Bind("/run/zed.state", "/run/zed.state", false, true).
Bind("/etc", "/fortify/etc").
Symlink("/fortify/etc/alsa", "/etc/alsa").
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
Symlink("/fortify/etc/default", "/etc/default").
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
Symlink("/fortify/etc/fonts", "/etc/fonts").
Symlink("/fortify/etc/fstab", "/etc/fstab").
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
Symlink("/fortify/etc/hostid", "/etc/hostid").
Symlink("/fortify/etc/hostname", "/etc/hostname").
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
Symlink("/fortify/etc/hosts", "/etc/hosts").
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
Symlink("/fortify/etc/issue", "/etc/issue").
Symlink("/fortify/etc/kbd", "/etc/kbd").
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
Symlink("/fortify/etc/localtime", "/etc/localtime").
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
Symlink("/fortify/etc/lvm", "/etc/lvm").
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
Symlink("/proc/mounts", "/etc/mtab").
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
Symlink("/fortify/etc/nix", "/etc/nix").
Symlink("/fortify/etc/nixos", "/etc/nixos").
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
Symlink("/fortify/etc/os-release", "/etc/os-release").
Symlink("/fortify/etc/pam", "/etc/pam").
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
Symlink("/fortify/etc/pki", "/etc/pki").
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
Symlink("/fortify/etc/profile", "/etc/profile").
Symlink("/fortify/etc/protocols", "/etc/protocols").
Symlink("/fortify/etc/qemu", "/etc/qemu").
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
Symlink("/fortify/etc/rpc", "/etc/rpc").
Symlink("/fortify/etc/samba", "/etc/samba").
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
Symlink("/fortify/etc/services", "/etc/services").
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
Symlink("/fortify/etc/shadow", "/etc/shadow").
Symlink("/fortify/etc/shells", "/etc/shells").
Symlink("/fortify/etc/ssh", "/etc/ssh").
Symlink("/fortify/etc/ssl", "/etc/ssl").
Symlink("/fortify/etc/static", "/etc/static").
Symlink("/fortify/etc/subgid", "/etc/subgid").
Symlink("/fortify/etc/subuid", "/etc/subuid").
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
Symlink("/fortify/etc/systemd", "/etc/systemd").
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
Symlink("/fortify/etc/udev", "/etc/udev").
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
Symlink("/fortify/etc/UPower", "/etc/UPower").
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
Symlink("/fortify/etc/X11", "/etc/X11").
Symlink("/fortify/etc/zfs", "/etc/zfs").
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
Bind("/tmp/fortify.1971/tmpdir/0", "/tmp", false, true).
Tmpfs("/tmp/fortify.1971", 1048576).
Tmpfs("/run/user", 1048576).
Tmpfs("/run/user/65534", 8388608).
Bind("/home/chronos", "/home/chronos", false, true).
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "/etc/passwd").
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "/etc/group").
Tmpfs("/var/run/nscd", 8192),
},
{
"nixos permissive defaults chromium", new(stubNixOS),
&fst.Config{
ID: "org.chromium.Chromium",
Command: []string{"/run/current-system/sw/bin/zsh", "-c", "exec chromium "},
Confinement: fst.ConfinementConfig{
AppID: 9,
Groups: []string{"video"},
Username: "chronos",
Outer: "/home/chronos",
SessionBus: &dbus.Config{
Talk: []string{
"org.freedesktop.Notifications",
"org.freedesktop.FileManager1",
"org.freedesktop.ScreenSaver",
"org.freedesktop.secrets",
"org.kde.kwalletd5",
"org.kde.kwalletd6",
"org.gnome.SessionManager",
},
Own: []string{
"org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*",
},
Call: map[string]string{
"org.freedesktop.portal.*": "*",
},
Broadcast: map[string]string{
"org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
},
Filter: true,
},
SystemBus: &dbus.Config{
Talk: []string{
"org.bluez",
"org.freedesktop.Avahi",
"org.freedesktop.UPower",
},
Filter: true,
},
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
},
},
fst.ID{
0xeb, 0xf0, 0x83, 0xd1,
0xb1, 0x75, 0x91, 0x17,
0x82, 0xd4, 0x13, 0x36,
0x9b, 0x64, 0xce, 0x7c,
},
system.New(1000009).
Ensure("/tmp/fortify.1971", 0711).
Ephemeral(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c", 0711).
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
Ensure("/tmp/fortify.1971/tmpdir/9", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/9", acl.Read, acl.Write, acl.Execute).
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
Ephemeral(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", acl.Execute).
WriteType(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/passwd", "chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n").
WriteType(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/group", "fortify:x:65534:\n").
Ensure("/tmp/fortify.1971/wayland", 0711).
Wayland("/tmp/fortify.1971/wayland/ebf083d1b175911782d413369b64ce7c", "/run/user/1971/wayland-0", "org.chromium.Chromium", "ebf083d1b175911782d413369b64ce7c").
Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse").
CopyFile("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie", "/home/ophestra/xdg/config/pulse/cookie").
MustProxyDBus("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", &dbus.Config{
Talk: []string{
"org.freedesktop.Notifications",
"org.freedesktop.FileManager1",
"org.freedesktop.ScreenSaver",
"org.freedesktop.secrets",
"org.kde.kwalletd5",
"org.kde.kwalletd6",
"org.gnome.SessionManager",
},
Own: []string{
"org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
"org.mpris.MediaPlayer2.chromium.*",
},
Call: map[string]string{
"org.freedesktop.portal.*": "*",
},
Broadcast: map[string]string{
"org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
},
Filter: true,
}, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", &dbus.Config{
Talk: []string{
"org.bluez",
"org.freedesktop.Avahi",
"org.freedesktop.UPower",
},
Filter: true,
}).
UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", acl.Read, acl.Write).
UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", acl.Read, acl.Write),
(&bwrap.Config{
Net: true,
UserNS: true,
Chdir: "/home/chronos",
Clearenv: true,
SetEnv: map[string]string{
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/65534/bus",
"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/run/dbus/system_bus_socket",
"HOME": "/home/chronos",
"PULSE_COOKIE": "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie",
"PULSE_SERVER": "unix:/run/user/65534/pulse/native",
"SHELL": "/run/current-system/sw/bin/zsh",
"TERM": "xterm-256color",
"USER": "chronos",
"WAYLAND_DISPLAY": "/run/user/65534/wayland-0",
"XDG_RUNTIME_DIR": "/run/user/65534",
"XDG_SESSION_CLASS": "user",
"XDG_SESSION_TYPE": "tty",
},
Chmod: make(bwrap.ChmodConfig),
DieWithParent: true,
AsInit: true,
}).SetUID(65534).SetGID(65534).
Procfs("/proc").
Tmpfs("/fortify", 4096).
DevTmpfs("/dev").Mqueue("/dev/mqueue").
Bind("/bin", "/bin", false, true).
Bind("/boot", "/boot", false, true).
Bind("/home", "/home", false, true).
Bind("/lib", "/lib", false, true).
Bind("/lib64", "/lib64", false, true).
Bind("/nix", "/nix", false, true).
Bind("/root", "/root", false, true).
Bind("/srv", "/srv", false, true).
Bind("/sys", "/sys", false, true).
Bind("/usr", "/usr", false, true).
Bind("/var", "/var", false, true).
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
Bind("/run/binfmt", "/run/binfmt", false, true).
Bind("/run/booted-system", "/run/booted-system", false, true).
Bind("/run/credentials", "/run/credentials", false, true).
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
Bind("/run/current-system", "/run/current-system", false, true).
Bind("/run/host", "/run/host", false, true).
Bind("/run/keys", "/run/keys", false, true).
Bind("/run/libvirt", "/run/libvirt", false, true).
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
Bind("/run/lock", "/run/lock", false, true).
Bind("/run/log", "/run/log", false, true).
Bind("/run/lvm", "/run/lvm", false, true).
Bind("/run/mount", "/run/mount", false, true).
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
Bind("/run/nginx", "/run/nginx", false, true).
Bind("/run/nixos", "/run/nixos", false, true).
Bind("/run/nscd", "/run/nscd", false, true).
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
Bind("/run/pppd", "/run/pppd", false, true).
Bind("/run/resolvconf", "/run/resolvconf", false, true).
Bind("/run/sddm", "/run/sddm", false, true).
Bind("/run/store", "/run/store", false, true).
Bind("/run/syncoid", "/run/syncoid", false, true).
Bind("/run/system", "/run/system", false, true).
Bind("/run/systemd", "/run/systemd", false, true).
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
Bind("/run/udev", "/run/udev", false, true).
Bind("/run/udisks2", "/run/udisks2", false, true).
Bind("/run/utmp", "/run/utmp", false, true).
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
Bind("/run/wrappers", "/run/wrappers", false, true).
Bind("/run/zed.pid", "/run/zed.pid", false, true).
Bind("/run/zed.state", "/run/zed.state", false, true).
Bind("/dev/dri", "/dev/dri", true, true, true).
Bind("/etc", "/fortify/etc").
Symlink("/fortify/etc/alsa", "/etc/alsa").
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
Symlink("/fortify/etc/default", "/etc/default").
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
Symlink("/fortify/etc/fonts", "/etc/fonts").
Symlink("/fortify/etc/fstab", "/etc/fstab").
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
Symlink("/fortify/etc/hostid", "/etc/hostid").
Symlink("/fortify/etc/hostname", "/etc/hostname").
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
Symlink("/fortify/etc/hosts", "/etc/hosts").
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
Symlink("/fortify/etc/issue", "/etc/issue").
Symlink("/fortify/etc/kbd", "/etc/kbd").
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
Symlink("/fortify/etc/localtime", "/etc/localtime").
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
Symlink("/fortify/etc/lvm", "/etc/lvm").
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
Symlink("/proc/mounts", "/etc/mtab").
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
Symlink("/fortify/etc/nix", "/etc/nix").
Symlink("/fortify/etc/nixos", "/etc/nixos").
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
Symlink("/fortify/etc/os-release", "/etc/os-release").
Symlink("/fortify/etc/pam", "/etc/pam").
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
Symlink("/fortify/etc/pki", "/etc/pki").
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
Symlink("/fortify/etc/profile", "/etc/profile").
Symlink("/fortify/etc/protocols", "/etc/protocols").
Symlink("/fortify/etc/qemu", "/etc/qemu").
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
Symlink("/fortify/etc/rpc", "/etc/rpc").
Symlink("/fortify/etc/samba", "/etc/samba").
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
Symlink("/fortify/etc/services", "/etc/services").
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
Symlink("/fortify/etc/shadow", "/etc/shadow").
Symlink("/fortify/etc/shells", "/etc/shells").
Symlink("/fortify/etc/ssh", "/etc/ssh").
Symlink("/fortify/etc/ssl", "/etc/ssl").
Symlink("/fortify/etc/static", "/etc/static").
Symlink("/fortify/etc/subgid", "/etc/subgid").
Symlink("/fortify/etc/subuid", "/etc/subuid").
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
Symlink("/fortify/etc/systemd", "/etc/systemd").
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
Symlink("/fortify/etc/udev", "/etc/udev").
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
Symlink("/fortify/etc/UPower", "/etc/UPower").
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
Symlink("/fortify/etc/X11", "/etc/X11").
Symlink("/fortify/etc/zfs", "/etc/zfs").
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
Bind("/tmp/fortify.1971/tmpdir/9", "/tmp", false, true).
Tmpfs("/tmp/fortify.1971", 1048576).
Tmpfs("/run/user", 1048576).
Tmpfs("/run/user/65534", 8388608).
Bind("/home/chronos", "/home/chronos", false, true).
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/passwd", "/etc/passwd").
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/group", "/etc/group").
Bind("/tmp/fortify.1971/wayland/ebf083d1b175911782d413369b64ce7c", "/run/user/65534/wayland-0").
Bind("/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse", "/run/user/65534/pulse/native").
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie", "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie").
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", "/run/user/65534/bus").
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", "/run/dbus/system_bus_socket").
Tmpfs("/var/run/nscd", 8192),
},
}

View File

@ -0,0 +1,153 @@
package app_test
import (
"fmt"
"io"
"io/fs"
"os/user"
"strconv"
"git.gensokyo.uk/security/fortify/internal/linux"
)
// fs methods are not implemented using a real FS
// to help better understand filesystem access behaviour
type stubNixOS struct {
lookPathErr map[string]error
usernameErr map[string]error
}
func (s *stubNixOS) Geteuid() int {
return 1971
}
func (s *stubNixOS) LookupEnv(key string) (string, bool) {
switch key {
case "SHELL":
return "/run/current-system/sw/bin/zsh", true
case "TERM":
return "xterm-256color", true
case "WAYLAND_DISPLAY":
return "wayland-0", true
case "PULSE_COOKIE":
return "", false
case "HOME":
return "/home/ophestra", true
case "XDG_CONFIG_HOME":
return "/home/ophestra/xdg/config", true
default:
panic(fmt.Sprintf("attempted to access unexpected environment variable %q", key))
}
}
func (s *stubNixOS) TempDir() string {
return "/tmp"
}
func (s *stubNixOS) LookPath(file string) (string, error) {
if s.lookPathErr != nil {
if err, ok := s.lookPathErr[file]; ok {
return "", err
}
}
switch file {
case "sudo":
return "/run/wrappers/bin/sudo", nil
case "machinectl":
return "/home/ophestra/.nix-profile/bin/machinectl", nil
default:
panic(fmt.Sprintf("attempted to look up unexpected executable %q", file))
}
}
func (s *stubNixOS) Executable() (string, error) {
return "/home/ophestra/.nix-profile/bin/fortify", nil
}
func (s *stubNixOS) LookupGroup(name string) (*user.Group, error) {
switch name {
case "video":
return &user.Group{Gid: "26", Name: "video"}, nil
default:
return nil, user.UnknownGroupError(name)
}
}
func (s *stubNixOS) ReadDir(name string) ([]fs.DirEntry, error) {
switch name {
case "/":
return stubDirEntries("bin", "boot", "dev", "etc", "home", "lib",
"lib64", "nix", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var")
case "/run":
return stubDirEntries("agetty.reload", "binfmt", "booted-system",
"credentials", "cryptsetup", "current-system", "dbus", "host", "keys",
"libvirt", "libvirtd.pid", "lock", "log", "lvm", "mount", "NetworkManager",
"nginx", "nixos", "nscd", "opengl-driver", "pppd", "resolvconf", "sddm",
"store", "syncoid", "system", "systemd", "tmpfiles.d", "udev", "udisks2",
"user", "utmp", "virtlogd.pid", "wrappers", "zed.pid", "zed.state")
case "/etc":
return stubDirEntries("alsa", "bashrc", "binfmt.d", "dbus-1", "default",
"ethertypes", "fonts", "fstab", "fuse.conf", "group", "host.conf", "hostid",
"hostname", "hostname.CHECKSUM", "hosts", "inputrc", "ipsec.d", "issue", "kbd",
"libblockdev", "locale.conf", "localtime", "login.defs", "lsb-release", "lvm",
"machine-id", "man_db.conf", "modprobe.d", "modules-load.d", "mtab", "nanorc",
"netgroup", "NetworkManager", "nix", "nixos", "NIXOS", "nscd.conf", "nsswitch.conf",
"opensnitchd", "os-release", "pam", "pam.d", "passwd", "pipewire", "pki", "polkit-1",
"profile", "protocols", "qemu", "resolv.conf", "resolvconf.conf", "rpc", "samba",
"sddm.conf", "secureboot", "services", "set-environment", "shadow", "shells", "ssh",
"ssl", "static", "subgid", "subuid", "sudoers", "sysctl.d", "systemd", "terminfo",
"tmpfiles.d", "udev", "udisks2", "UPower", "vconsole.conf", "X11", "zfs", "zinputrc",
"zoneinfo", "zprofile", "zshenv", "zshrc")
default:
panic(fmt.Sprintf("attempted to read unexpected directory %q", name))
}
}
func (s *stubNixOS) Stat(name string) (fs.FileInfo, error) {
switch name {
case "/var/run/nscd":
return nil, nil
case "/run/user/1971/pulse":
return nil, nil
case "/run/user/1971/pulse/native":
return stubFileInfoMode(0666), nil
case "/home/ophestra/.pulse-cookie":
return stubFileInfoIsDir(true), nil
case "/home/ophestra/xdg/config/pulse/cookie":
return stubFileInfoIsDir(false), nil
default:
panic(fmt.Sprintf("attempted to stat unexpected path %q", name))
}
}
func (s *stubNixOS) Open(name string) (fs.File, error) {
switch name {
default:
panic(fmt.Sprintf("attempted to open unexpected file %q", name))
}
}
func (s *stubNixOS) Exit(code int) {
panic("called exit on stub with code " + strconv.Itoa(code))
}
func (s *stubNixOS) Stdout() io.Writer {
panic("requested stdout")
}
func (s *stubNixOS) Paths() linux.Paths {
return linux.Paths{
SharePath: "/tmp/fortify.1971",
RuntimePath: "/run/user/1971",
RunDirPath: "/run/user/1971/fortify",
}
}
func (s *stubNixOS) Uid(aid int) (int, error) {
return 1000000 + 0*10000 + aid, nil
}
func (s *stubNixOS) SdBooted() bool {
return true
}

135
internal/app/app_test.go Normal file
View File

@ -0,0 +1,135 @@
package app_test
import (
"io/fs"
"reflect"
"testing"
"time"
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/app"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
type sealTestCase struct {
name string
os linux.System
config *fst.Config
id fst.ID
wantSys *system.I
wantBwrap *bwrap.Config
}
func TestApp(t *testing.T) {
testCases := append(testCasesPd, testCasesNixos...)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
a := app.NewWithID(tc.id, tc.os)
if !t.Run("seal", func(t *testing.T) {
if err := a.Seal(tc.config); err != nil {
t.Errorf("Seal: error = %v", err)
}
}) {
return
}
gotSys, gotBwrap := app.AppSystemBwrap(a)
t.Run("compare sys", func(t *testing.T) {
if !gotSys.Equal(tc.wantSys) {
t.Errorf("Seal: sys = %#v, want %#v",
gotSys, tc.wantSys)
}
})
t.Run("compare bwrap", func(t *testing.T) {
if !reflect.DeepEqual(gotBwrap, tc.wantBwrap) {
t.Errorf("seal: bwrap = %#v, want %#v",
gotBwrap, tc.wantBwrap)
}
})
})
}
}
func stubDirEntries(names ...string) (e []fs.DirEntry, err error) {
e = make([]fs.DirEntry, len(names))
for i, name := range names {
e[i] = stubDirEntryPath(name)
}
return
}
type stubDirEntryPath string
func (p stubDirEntryPath) Name() string {
return string(p)
}
func (p stubDirEntryPath) IsDir() bool {
panic("attempted to call IsDir")
}
func (p stubDirEntryPath) Type() fs.FileMode {
panic("attempted to call Type")
}
func (p stubDirEntryPath) Info() (fs.FileInfo, error) {
panic("attempted to call Info")
}
type stubFileInfoMode fs.FileMode
func (s stubFileInfoMode) Name() string {
panic("attempted to call Name")
}
func (s stubFileInfoMode) Size() int64 {
panic("attempted to call Size")
}
func (s stubFileInfoMode) Mode() fs.FileMode {
return fs.FileMode(s)
}
func (s stubFileInfoMode) ModTime() time.Time {
panic("attempted to call ModTime")
}
func (s stubFileInfoMode) IsDir() bool {
panic("attempted to call IsDir")
}
func (s stubFileInfoMode) Sys() any {
panic("attempted to call Sys")
}
type stubFileInfoIsDir bool
func (s stubFileInfoIsDir) Name() string {
panic("attempted to call Name")
}
func (s stubFileInfoIsDir) Size() int64 {
panic("attempted to call Size")
}
func (s stubFileInfoIsDir) Mode() fs.FileMode {
panic("attempted to call Mode")
}
func (s stubFileInfoIsDir) ModTime() time.Time {
panic("attempted to call ModTime")
}
func (s stubFileInfoIsDir) IsDir() bool {
return bool(s)
}
func (s stubFileInfoIsDir) Sys() any {
panic("attempted to call Sys")
}

View File

@ -0,0 +1,20 @@
package app
import (
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
func NewWithID(id fst.ID, os linux.System) App {
a := new(app)
a.id = &id
a.os = os
return a
}
func AppSystemBwrap(a App) (*system.I, *bwrap.Config) {
v := a.(*app)
return v.seal.sys.I, v.seal.sys.bwrap
}

242
internal/app/seal.go Normal file
View File

@ -0,0 +1,242 @@
package app
import (
"errors"
"fmt"
"io/fs"
"path"
"regexp"
"strconv"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/fst"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/state"
"git.gensokyo.uk/security/fortify/internal/system"
)
var (
ErrConfig = errors.New("no configuration to seal")
ErrUser = errors.New("invalid aid")
ErrHome = errors.New("invalid home directory")
ErrName = errors.New("invalid username")
)
var posixUsername = regexp.MustCompilePOSIX("^[a-z_]([A-Za-z0-9_-]{0,31}|[A-Za-z0-9_-]{0,30}\\$)$")
// appSeal seals the application with child-related information
type appSeal struct {
// app unique ID string representation
id string
// dbus proxy message buffer retriever
dbusMsg func(f func(msgbuf []string))
// freedesktop application ID
fid string
// argv to start process with in the final confined environment
command []string
// persistent process state store
store state.Store
// process-specific share directory path
share string
// process-specific share directory path local to XDG_RUNTIME_DIR
shareLocal string
// pass-through enablement tracking from config
et system.Enablements
// wayland socket direct access
directWayland bool
// prevents sharing from happening twice
shared bool
// seal system-level component
sys *appSealSys
linux.Paths
// protected by upstream mutex
}
// Seal seals the app launch context
func (a *app) Seal(config *fst.Config) error {
a.lock.Lock()
defer a.lock.Unlock()
if a.seal != nil {
panic("app sealed twice")
}
if config == nil {
return fmsg.WrapError(ErrConfig,
"attempted to seal app with nil config")
}
// create seal
seal := new(appSeal)
// fetch system constants
seal.Paths = a.os.Paths()
// pass through config values
seal.id = a.id.String()
seal.fid = config.ID
seal.command = config.Command
// create seal system component
seal.sys = new(appSealSys)
// mapped uid
if config.Confinement.Sandbox != nil && config.Confinement.Sandbox.MapRealUID {
seal.sys.mappedID = a.os.Geteuid()
} else {
seal.sys.mappedID = 65534
}
seal.sys.mappedIDString = strconv.Itoa(seal.sys.mappedID)
seal.sys.runtime = path.Join("/run/user", seal.sys.mappedIDString)
// validate uid and set user info
if config.Confinement.AppID < 0 || config.Confinement.AppID > 9999 {
return fmsg.WrapError(ErrUser,
fmt.Sprintf("aid %d out of range", config.Confinement.AppID))
} else {
seal.sys.user = appUser{
aid: config.Confinement.AppID,
as: strconv.Itoa(config.Confinement.AppID),
data: config.Confinement.Outer,
home: config.Confinement.Inner,
username: config.Confinement.Username,
}
if seal.sys.user.username == "" {
seal.sys.user.username = "chronos"
} else if !posixUsername.MatchString(seal.sys.user.username) {
return fmsg.WrapError(ErrName,
fmt.Sprintf("invalid user name %q", seal.sys.user.username))
}
if seal.sys.user.data == "" || !path.IsAbs(seal.sys.user.data) {
return fmsg.WrapError(ErrHome,
fmt.Sprintf("invalid home directory %q", seal.sys.user.data))
}
if seal.sys.user.home == "" {
seal.sys.user.home = seal.sys.user.data
}
// invoke fsu for full uid
if u, err := a.os.Uid(seal.sys.user.aid); err != nil {
return fmsg.WrapErrorSuffix(err,
"cannot obtain uid from fsu:")
} else {
seal.sys.user.uid = u
seal.sys.user.us = strconv.Itoa(u)
}
// resolve supplementary group ids from names
seal.sys.user.supp = make([]string, len(config.Confinement.Groups))
for i, name := range config.Confinement.Groups {
if g, err := a.os.LookupGroup(name); err != nil {
return fmsg.WrapError(err,
fmt.Sprintf("unknown group %q", name))
} else {
seal.sys.user.supp[i] = g.Gid
}
}
}
// map sandbox config to bwrap
if config.Confinement.Sandbox == nil {
fmsg.VPrintln("sandbox configuration not supplied, PROCEED WITH CAUTION")
// permissive defaults
conf := &fst.SandboxConfig{
UserNS: true,
Net: true,
NoNewSession: true,
AutoEtc: true,
}
// bind entries in /
if d, err := a.os.ReadDir("/"); err != nil {
return err
} else {
b := make([]*fst.FilesystemConfig, 0, len(d))
for _, ent := range d {
p := "/" + ent.Name()
switch p {
case "/proc":
case "/dev":
case "/run":
case "/tmp":
case "/mnt":
case "/etc":
default:
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
}
}
conf.Filesystem = append(conf.Filesystem, b...)
}
// bind entries in /run
if d, err := a.os.ReadDir("/run"); err != nil {
return err
} else {
b := make([]*fst.FilesystemConfig, 0, len(d))
for _, ent := range d {
name := ent.Name()
switch name {
case "user":
case "dbus":
default:
p := "/run/" + name
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
}
}
conf.Filesystem = append(conf.Filesystem, b...)
}
// hide nscd from sandbox if present
nscd := "/var/run/nscd"
if _, err := a.os.Stat(nscd); !errors.Is(err, fs.ErrNotExist) {
conf.Override = append(conf.Override, nscd)
}
// bind GPU stuff
if config.Confinement.Enablements.Has(system.EX11) || config.Confinement.Enablements.Has(system.EWayland) {
conf.Filesystem = append(conf.Filesystem, &fst.FilesystemConfig{Src: "/dev/dri", Device: true})
}
config.Confinement.Sandbox = conf
}
seal.directWayland = config.Confinement.Sandbox.DirectWayland
if b, err := config.Confinement.Sandbox.Bwrap(a.os); err != nil {
return err
} else {
seal.sys.bwrap = b
}
seal.sys.override = config.Confinement.Sandbox.Override
if seal.sys.bwrap.SetEnv == nil {
seal.sys.bwrap.SetEnv = make(map[string]string)
}
// open process state store
// the simple store only starts holding an open file after first action
// store activity begins after Start is called and must end before Wait
seal.store = state.NewMulti(seal.RunDirPath)
// initialise system interface with full uid
seal.sys.I = system.New(seal.sys.user.uid)
// pass through enablements
seal.et = config.Confinement.Enablements
// this method calls all share methods in sequence
if err := seal.shareAll([2]*dbus.Config{config.Confinement.SessionBus, config.Confinement.SystemBus}, a.os); err != nil {
return err
}
// verbose log seal information
fmsg.VPrintf("created application seal for uid %s (%s) groups: %v, command: %s",
seal.sys.user.us, seal.sys.user.username, config.Confinement.Groups, config.Command)
// seal app and release lock
a.seal = seal
a.ct = newAppCt(config)
return nil
}

View File

@ -0,0 +1,44 @@
package app
import (
"path"
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/internal/system"
)
const (
dbusSessionBusAddress = "DBUS_SESSION_BUS_ADDRESS"
dbusSystemBusAddress = "DBUS_SYSTEM_BUS_ADDRESS"
)
func (seal *appSeal) shareDBus(config [2]*dbus.Config) error {
if !seal.et.Has(system.EDBus) {
return nil
}
// downstream socket paths
sessionPath, systemPath := path.Join(seal.share, "bus"), path.Join(seal.share, "system_bus_socket")
// configure dbus proxy
if f, err := seal.sys.ProxyDBus(config[0], config[1], sessionPath, systemPath); err != nil {
return err
} else {
seal.dbusMsg = f
}
// share proxy sockets
sessionInner := path.Join(seal.sys.runtime, "bus")
seal.sys.bwrap.SetEnv[dbusSessionBusAddress] = "unix:path=" + sessionInner
seal.sys.bwrap.Bind(sessionPath, sessionInner)
seal.sys.UpdatePerm(sessionPath, acl.Read, acl.Write)
if config[1] != nil {
systemInner := "/run/dbus/system_bus_socket"
seal.sys.bwrap.SetEnv[dbusSystemBusAddress] = "unix:path=" + systemInner
seal.sys.bwrap.Bind(systemPath, systemInner)
seal.sys.UpdatePerm(systemPath, acl.Read, acl.Write)
}
return nil
}

View File

@ -0,0 +1,81 @@
package app
import (
"errors"
"path"
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
const (
term = "TERM"
display = "DISPLAY"
// https://manpages.debian.org/experimental/libwayland-doc/wl_display_connect.3.en.html
waylandDisplay = "WAYLAND_DISPLAY"
)
var (
ErrWayland = errors.New(waylandDisplay + " unset")
ErrXDisplay = errors.New(display + " unset")
)
func (seal *appSeal) shareDisplay(os linux.System) error {
// pass $TERM to launcher
if t, ok := os.LookupEnv(term); ok {
seal.sys.bwrap.SetEnv[term] = t
}
// set up wayland
if seal.et.Has(system.EWayland) {
var wp string
if wd, ok := os.LookupEnv(waylandDisplay); !ok {
return fmsg.WrapError(ErrWayland,
"WAYLAND_DISPLAY is not set")
} else {
wp = path.Join(seal.RuntimePath, wd)
}
w := path.Join(seal.sys.runtime, "wayland-0")
seal.sys.bwrap.SetEnv[waylandDisplay] = w
if seal.directWayland {
// hardlink wayland socket
wpi := path.Join(seal.shareLocal, "wayland")
seal.sys.Link(wp, wpi)
seal.sys.bwrap.Bind(wpi, w)
// ensure Wayland socket ACL (e.g. `/run/user/%d/wayland-%d`)
seal.sys.UpdatePermType(system.EWayland, wp, acl.Read, acl.Write, acl.Execute)
} else {
wc := path.Join(seal.SharePath, "wayland")
wt := path.Join(wc, seal.id)
seal.sys.Ensure(wc, 0711)
appID := seal.fid
if appID == "" {
// use instance ID in case app id is not set
appID = "moe.ophivana.fortify." + seal.id
}
seal.sys.Wayland(wt, wp, appID, seal.id)
seal.sys.bwrap.Bind(wt, w)
}
}
// set up X11
if seal.et.Has(system.EX11) {
// discover X11 and grant user permission via the `ChangeHosts` command
if d, ok := os.LookupEnv(display); !ok {
return fmsg.WrapError(ErrXDisplay,
"DISPLAY is not set")
} else {
seal.sys.ChangeHosts("#" + seal.sys.user.us)
seal.sys.bwrap.SetEnv[display] = d
seal.sys.bwrap.Bind("/tmp/.X11-unix", "/tmp/.X11-unix")
}
}
return nil
}

117
internal/app/share.pulse.go Normal file
View File

@ -0,0 +1,117 @@
package app
import (
"errors"
"fmt"
"io/fs"
"path"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
const (
pulseServer = "PULSE_SERVER"
pulseCookie = "PULSE_COOKIE"
home = "HOME"
xdgConfigHome = "XDG_CONFIG_HOME"
)
var (
ErrPulseCookie = errors.New("pulse cookie not present")
ErrPulseSocket = errors.New("pulse socket not present")
ErrPulseMode = errors.New("unexpected pulse socket mode")
)
func (seal *appSeal) sharePulse(os linux.System) error {
if !seal.et.Has(system.EPulse) {
return nil
}
// check PulseAudio directory presence (e.g. `/run/user/%d/pulse`)
pd := path.Join(seal.RuntimePath, "pulse")
ps := path.Join(pd, "native")
if _, err := os.Stat(pd); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return fmsg.WrapErrorSuffix(err,
fmt.Sprintf("cannot access PulseAudio directory %q:", pd))
}
return fmsg.WrapError(ErrPulseSocket,
fmt.Sprintf("PulseAudio directory %q not found", pd))
}
// check PulseAudio socket permission (e.g. `/run/user/%d/pulse/native`)
if s, err := os.Stat(ps); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return fmsg.WrapErrorSuffix(err,
fmt.Sprintf("cannot access PulseAudio socket %q:", ps))
}
return fmsg.WrapError(ErrPulseSocket,
fmt.Sprintf("PulseAudio directory %q found but socket does not exist", pd))
} else {
if m := s.Mode(); m&0o006 != 0o006 {
return fmsg.WrapError(ErrPulseMode,
fmt.Sprintf("unexpected permissions on %q:", ps), m)
}
}
// hard link pulse socket into target-executable share
psi := path.Join(seal.shareLocal, "pulse")
p := path.Join(seal.sys.runtime, "pulse", "native")
seal.sys.Link(ps, psi)
seal.sys.bwrap.Bind(psi, p)
seal.sys.bwrap.SetEnv[pulseServer] = "unix:" + p
// publish current user's pulse cookie for target user
if src, err := discoverPulseCookie(os); err != nil {
return err
} else {
dst := path.Join(seal.share, "pulse-cookie")
seal.sys.bwrap.SetEnv[pulseCookie] = dst
seal.sys.CopyFile(dst, src)
seal.sys.bwrap.Bind(dst, dst)
}
return nil
}
// discoverPulseCookie attempts various standard methods to discover the current user's PulseAudio authentication cookie
func discoverPulseCookie(os linux.System) (string, error) {
if p, ok := os.LookupEnv(pulseCookie); ok {
return p, nil
}
// dotfile $HOME/.pulse-cookie
if p, ok := os.LookupEnv(home); ok {
p = path.Join(p, ".pulse-cookie")
if s, err := os.Stat(p); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return p, fmsg.WrapErrorSuffix(err,
fmt.Sprintf("cannot access PulseAudio cookie %q:", p))
}
// not found, try next method
} else if !s.IsDir() {
return p, nil
}
}
// $XDG_CONFIG_HOME/pulse/cookie
if p, ok := os.LookupEnv(xdgConfigHome); ok {
p = path.Join(p, "pulse", "cookie")
if s, err := os.Stat(p); err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return p, fmsg.WrapErrorSuffix(err,
fmt.Sprintf("cannot access PulseAudio cookie %q:", p))
}
// not found, try next method
} else if !s.IsDir() {
return p, nil
}
}
return "", fmsg.WrapError(ErrPulseCookie,
fmt.Sprintf("cannot locate PulseAudio cookie (tried $%s, $%s/pulse/cookie, $%s/.pulse-cookie)",
pulseCookie, xdgConfigHome, home))
}

View File

@ -0,0 +1,39 @@
package app
import (
"path"
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/internal/system"
)
const (
xdgRuntimeDir = "XDG_RUNTIME_DIR"
xdgSessionClass = "XDG_SESSION_CLASS"
xdgSessionType = "XDG_SESSION_TYPE"
)
// shareRuntime queues actions for sharing/ensuring the runtime and share directories
func (seal *appSeal) shareRuntime() {
// mount tmpfs on inner runtime (e.g. `/run/user/%d`)
seal.sys.bwrap.Tmpfs("/run/user", 1*1024*1024)
seal.sys.bwrap.Tmpfs(seal.sys.runtime, 8*1024*1024)
// point to inner runtime path `/run/user/%d`
seal.sys.bwrap.SetEnv[xdgRuntimeDir] = seal.sys.runtime
seal.sys.bwrap.SetEnv[xdgSessionClass] = "user"
seal.sys.bwrap.SetEnv[xdgSessionType] = "tty"
// ensure RunDir (e.g. `/run/user/%d/fortify`)
seal.sys.Ensure(seal.RunDirPath, 0700)
seal.sys.UpdatePermType(system.User, seal.RunDirPath, acl.Execute)
// ensure runtime directory ACL (e.g. `/run/user/%d`)
seal.sys.Ensure(seal.RuntimePath, 0700) // ensure this dir in case XDG_RUNTIME_DIR is unset
seal.sys.UpdatePermType(system.User, seal.RuntimePath, acl.Execute)
// ensure process-specific share local to XDG_RUNTIME_DIR (e.g. `/run/user/%d/fortify/%s`)
seal.shareLocal = path.Join(seal.RunDirPath, seal.id)
seal.sys.Ephemeral(system.Process, seal.shareLocal, 0700)
seal.sys.UpdatePerm(seal.shareLocal, acl.Execute)
}

View File

@ -0,0 +1,77 @@
package app
import (
"path"
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
const (
shell = "SHELL"
)
// shareSystem queues various system-related actions
func (seal *appSeal) shareSystem() {
// ensure Share (e.g. `/tmp/fortify.%d`)
// acl is unnecessary as this directory is world executable
seal.sys.Ensure(seal.SharePath, 0711)
// ensure process-specific share (e.g. `/tmp/fortify.%d/%s`)
// acl is unnecessary as this directory is world executable
seal.share = path.Join(seal.SharePath, seal.id)
seal.sys.Ephemeral(system.Process, seal.share, 0711)
// ensure child tmpdir parent directory (e.g. `/tmp/fortify.%d/tmpdir`)
targetTmpdirParent := path.Join(seal.SharePath, "tmpdir")
seal.sys.Ensure(targetTmpdirParent, 0700)
seal.sys.UpdatePermType(system.User, targetTmpdirParent, acl.Execute)
// ensure child tmpdir (e.g. `/tmp/fortify.%d/tmpdir/%d`)
targetTmpdir := path.Join(targetTmpdirParent, seal.sys.user.as)
seal.sys.Ensure(targetTmpdir, 01700)
seal.sys.UpdatePermType(system.User, targetTmpdir, acl.Read, acl.Write, acl.Execute)
seal.sys.bwrap.Bind(targetTmpdir, "/tmp", false, true)
// mount tmpfs on inner shared directory (e.g. `/tmp/fortify.%d`)
seal.sys.bwrap.Tmpfs(seal.SharePath, 1*1024*1024)
}
func (seal *appSeal) sharePasswd(os linux.System) {
// look up shell
sh := "/bin/sh"
if s, ok := os.LookupEnv(shell); ok {
seal.sys.bwrap.SetEnv[shell] = s
sh = s
}
// generate /etc/passwd
passwdPath := path.Join(seal.share, "passwd")
username := "chronos"
if seal.sys.user.username != "" {
username = seal.sys.user.username
}
homeDir := "/var/empty"
if seal.sys.user.home != "" {
homeDir = seal.sys.user.home
}
// bind home directory
seal.sys.bwrap.Bind(seal.sys.user.data, homeDir, false, true)
seal.sys.bwrap.Chdir = homeDir
seal.sys.bwrap.SetEnv["USER"] = username
seal.sys.bwrap.SetEnv["HOME"] = homeDir
passwd := username + ":x:" + seal.sys.mappedIDString + ":" + seal.sys.mappedIDString + ":Fortify:" + homeDir + ":" + sh + "\n"
seal.sys.Write(passwdPath, passwd)
// write /etc/group
groupPath := path.Join(seal.share, "group")
seal.sys.Write(groupPath, "fortify:x:"+seal.sys.mappedIDString+":\n")
// bind /etc/passwd and /etc/group
seal.sys.bwrap.Bind(passwdPath, "/etc/passwd")
seal.sys.bwrap.Bind(groupPath, "/etc/group")
}

265
internal/app/start.go Normal file
View File

@ -0,0 +1,265 @@
package app
import (
"errors"
"fmt"
"os/exec"
"path/filepath"
"strings"
shim0 "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
"git.gensokyo.uk/security/fortify/cmd/fshim/ipc/shim"
"git.gensokyo.uk/security/fortify/helper"
"git.gensokyo.uk/security/fortify/internal/fmsg"
"git.gensokyo.uk/security/fortify/internal/state"
"git.gensokyo.uk/security/fortify/internal/system"
)
// Start selects a user switcher and starts shim.
// Note that Wait must be called regardless of error returned by Start.
func (a *app) Start() error {
a.lock.Lock()
defer a.lock.Unlock()
// resolve exec paths
shimExec := [2]string{helper.BubblewrapName}
if len(a.seal.command) > 0 {
shimExec[1] = a.seal.command[0]
}
for i, n := range shimExec {
if len(n) == 0 {
continue
}
if filepath.Base(n) == n {
if s, err := exec.LookPath(n); err == nil {
shimExec[i] = s
} else {
return fmsg.WrapError(err,
fmt.Sprintf("executable file %q not found in $PATH", n))
}
}
}
// construct shim manager
a.shim = shim.New(
uint32(a.seal.sys.UID()),
a.seal.sys.user.as,
a.seal.sys.user.supp,
&shim0.Payload{
Argv: a.seal.command,
Exec: shimExec,
Bwrap: a.seal.sys.bwrap,
Verbose: fmsg.Verbose(),
},
)
// startup will go ahead, commit system setup
if err := a.seal.sys.Commit(); err != nil {
return err
}
a.seal.sys.needRevert = true
// export sync pipe from sys
a.seal.sys.bwrap.SetSync(a.seal.sys.Sync())
if startTime, err := a.shim.Start(); err != nil {
return err
} else {
// shim start and setup success, create process state
sd := state.State{
ID: *a.id,
PID: a.shim.Unwrap().Process.Pid,
Config: a.ct.Unwrap(),
Time: *startTime,
}
// register process state
var err0 = new(StateStoreError)
err0.Inner, err0.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(c state.Cursor) {
err0.InnerErr = c.Save(&sd)
})
a.seal.sys.saveState = true
return err0.equiv("cannot save process state:")
}
}
// StateStoreError is returned for a failed state save
type StateStoreError struct {
// whether inner function was called
Inner bool
// error returned by state.Store Do method
DoErr error
// error returned by state.Backend Save method
InnerErr error
// any other errors needing to be tracked
Err error
}
func (e *StateStoreError) equiv(a ...any) error {
if e.Inner && e.DoErr == nil && e.InnerErr == nil && e.Err == nil {
return nil
} else {
return fmsg.WrapErrorSuffix(e, a...)
}
}
func (e *StateStoreError) Error() string {
if e.Inner && e.InnerErr != nil {
return e.InnerErr.Error()
}
if e.DoErr != nil {
return e.DoErr.Error()
}
if e.Err != nil {
return e.Err.Error()
}
return "(nil)"
}
func (e *StateStoreError) Unwrap() (errs []error) {
errs = make([]error, 0, 3)
if e.DoErr != nil {
errs = append(errs, e.DoErr)
}
if e.InnerErr != nil {
errs = append(errs, e.InnerErr)
}
if e.Err != nil {
errs = append(errs, e.Err)
}
return
}
type RevertCompoundError interface {
Error() string
Unwrap() []error
}
func (a *app) Wait() (int, error) {
a.lock.Lock()
defer a.lock.Unlock()
if a.shim == nil {
fmsg.VPrintln("shim not initialised, skipping cleanup")
return 1, nil
}
var r int
if cmd := a.shim.Unwrap(); cmd == nil {
// failure prior to process start
r = 255
} else {
wait := make(chan error, 1)
go func() { wait <- cmd.Wait() }()
select {
// wait for process and resolve exit code
case err := <-wait:
if err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) {
// should be unreachable
a.waitErr = err
}
// store non-zero return code
r = exitError.ExitCode()
} else {
r = cmd.ProcessState.ExitCode()
}
fmsg.VPrintf("process %d exited with exit code %d", cmd.Process.Pid, r)
// alternative exit path when kill was unsuccessful
case err := <-a.shim.WaitFallback():
r = 255
if err != nil {
fmsg.Printf("cannot terminate shim on faulted setup: %v", err)
} else {
fmsg.VPrintln("alternative exit path selected")
}
}
}
// child process exited, resume output
fmsg.Resume()
// print queued up dbus messages
if a.seal.dbusMsg != nil {
a.seal.dbusMsg(func(msgbuf []string) {
for _, msg := range msgbuf {
fmsg.Println(msg)
}
})
}
// update store and revert app setup transaction
e := new(StateStoreError)
e.Inner, e.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(b state.Cursor) {
e.InnerErr = func() error {
// destroy defunct state entry
if cmd := a.shim.Unwrap(); cmd != nil && a.seal.sys.saveState {
if err := b.Destroy(*a.id); err != nil {
return err
}
}
// enablements of remaining launchers
rt, ec := new(system.Enablements), new(system.Criteria)
ec.Enablements = new(system.Enablements)
ec.Set(system.Process)
if states, err := b.Load(); err != nil {
return err
} else {
if l := len(states); l == 0 {
// cleanup globals as the final launcher
fmsg.VPrintln("no other launchers active, will clean up globals")
ec.Set(system.User)
} else {
fmsg.VPrintf("found %d active launchers, cleaning up without globals", l)
}
// accumulate capabilities of other launchers
for i, s := range states {
if s.Config != nil {
*rt |= s.Config.Confinement.Enablements
} else {
fmsg.Printf("state entry %d does not contain config", i)
}
}
}
// invert accumulated enablements for cleanup
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ {
if !rt.Has(i) {
ec.Set(i)
}
}
if fmsg.Verbose() {
labels := make([]string, 0, system.ELen+1)
for i := system.Enablement(0); i < system.Enablement(system.ELen+2); i++ {
if ec.Has(i) {
labels = append(labels, system.TypeString(i))
}
}
if len(labels) > 0 {
fmsg.VPrintln("reverting operations labelled", strings.Join(labels, ", "))
}
}
if a.seal.sys.needRevert {
if err := a.seal.sys.Revert(ec); err != nil {
return err.(RevertCompoundError)
}
}
return nil
}()
})
e.Err = a.seal.store.Close()
return r, e.equiv("error returned during cleanup:", e)
}

87
internal/app/system.go Normal file
View File

@ -0,0 +1,87 @@
package app
import (
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/helper/bwrap"
"git.gensokyo.uk/security/fortify/internal/linux"
"git.gensokyo.uk/security/fortify/internal/system"
)
// appSealSys encapsulates app seal behaviour with OS interactions
type appSealSys struct {
bwrap *bwrap.Config
// paths to override by mounting tmpfs over them
override []string
// default formatted XDG_RUNTIME_DIR of User
runtime string
// target user sealed from config
user appUser
// mapped uid and gid in user namespace
mappedID int
// string representation of mappedID
mappedIDString string
needRevert bool
saveState bool
*system.I
// protected by upstream mutex
}
type appUser struct {
// full uid resolved by fsu
uid int
// string representation of uid
us string
// supplementary group ids
supp []string
// application id
aid int
// string representation of aid
as string
// home directory host path
data string
// app user home directory
home string
// passwd database username
username string
}
// shareAll calls all share methods in sequence
func (seal *appSeal) shareAll(bus [2]*dbus.Config, os linux.System) error {
if seal.shared {
panic("seal shared twice")
}
seal.shared = true
seal.shareSystem()
seal.shareRuntime()
seal.sharePasswd(os)
if err := seal.shareDisplay(os); err != nil {
return err
}
if err := seal.sharePulse(os); err != nil {
return err
}
// ensure dbus session bus defaults
if bus[0] == nil {
bus[0] = dbus.NewConfig(seal.fid, true, true)
}
if err := seal.shareDBus(bus); err != nil {
return err
}
// queue overriding tmpfs at the end of seal.sys.bwrap.Filesystem
for _, dest := range seal.sys.override {
seal.sys.bwrap.Tmpfs(dest, 8*1024)
}
return nil
}

12
internal/comp.go Normal file
View File

@ -0,0 +1,12 @@
package internal
const compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
var (
Version = compPoison
)
// Check validates string value set at compile time.
func Check(s string) (string, bool) {
return s, s != compPoison && s != ""
}

97
internal/fmsg/defer.go Normal file
View File

@ -0,0 +1,97 @@
package fmsg
import (
"os"
"sync"
"sync/atomic"
)
var (
wstate atomic.Bool
dropped atomic.Uint64
withhold = make(chan struct{}, 1)
msgbuf = make(chan dOp, 64) // these ops are tiny so a large buffer is allocated for withholding output
dequeueOnce sync.Once
queueSync sync.WaitGroup
)
func dequeue() {
go func() {
for {
select {
case op := <-msgbuf:
op.Do()
queueSync.Done()
case <-withhold:
<-withhold
}
}
}()
}
// queue submits ops to msgbuf but drops messages
// when the buffer is full and dequeue is withholding
func queue(op dOp) {
queueSync.Add(1)
select {
case msgbuf <- op:
default:
// send the op anyway if not withholding
// as dequeue will get to it eventually
if !wstate.Load() {
msgbuf <- op
} else {
queueSync.Done()
// increment dropped message count
dropped.Add(1)
}
}
}
type dOp interface{ Do() }
func Exit(code int) {
queueSync.Wait()
os.Exit(code)
}
func Suspend() {
dequeueOnce.Do(dequeue)
if wstate.CompareAndSwap(false, true) {
queueSync.Wait()
withhold <- struct{}{}
}
}
func Resume() {
dequeueOnce.Do(dequeue)
if wstate.CompareAndSwap(true, false) {
withhold <- struct{}{}
if d := dropped.Swap(0); d != 0 {
Printf("dropped %d messages during withhold", d)
}
}
}
type dPrint []any
func (v dPrint) Do() {
std.Print(v...)
}
type dPrintf struct {
format string
v []any
}
func (d *dPrintf) Do() {
std.Printf(d.format, d.v...)
}
type dPrintln []any
func (v dPrintln) Do() {
std.Println(v...)
}

72
internal/fmsg/errors.go Normal file
View File

@ -0,0 +1,72 @@
package fmsg
import (
"fmt"
"reflect"
)
// baseError implements a basic error container
type baseError struct {
Err error
}
func (e *baseError) Error() string {
return e.Err.Error()
}
func (e *baseError) Unwrap() error {
return e.Err
}
// BaseError implements an error container with a user-facing message
type BaseError struct {
message string
baseError
}
// Message returns a user-facing error message
func (e *BaseError) Message() string {
return e.message
}
// WrapError wraps an error with a corresponding message.
func WrapError(err error, a ...any) error {
if err == nil {
return nil
}
return wrapError(err, fmt.Sprintln(a...))
}
// WrapErrorSuffix wraps an error with a corresponding message with err at the end of the message.
func WrapErrorSuffix(err error, a ...any) error {
if err == nil {
return nil
}
return wrapError(err, fmt.Sprintln(append(a, err)...))
}
// WrapErrorFunc wraps an error with a corresponding message returned by f.
func WrapErrorFunc(err error, f func(err error) string) error {
if err == nil {
return nil
}
return wrapError(err, f(err))
}
func wrapError(err error, message string) *BaseError {
return &BaseError{message, baseError{err}}
}
var (
baseErrorType = reflect.TypeFor[*BaseError]()
)
func AsBaseError(err error, target **BaseError) bool {
v := reflect.ValueOf(err)
if !v.CanConvert(baseErrorType) {
return false
}
*target = v.Convert(baseErrorType).Interface().(*BaseError)
return true
}

40
internal/fmsg/fmsg.go Normal file
View File

@ -0,0 +1,40 @@
// Package fmsg provides various functions for output messages.
package fmsg
import (
"log"
"os"
)
var std = log.New(os.Stderr, "fortify: ", 0)
func SetPrefix(prefix string) {
prefix += ": "
std.SetPrefix(prefix)
std.SetPrefix(prefix)
}
func Print(v ...any) {
dequeueOnce.Do(dequeue)
queue(dPrint(v))
}
func Printf(format string, v ...any) {
dequeueOnce.Do(dequeue)
queue(&dPrintf{format, v})
}
func Println(v ...any) {
dequeueOnce.Do(dequeue)
queue(dPrintln(v))
}
func Fatal(v ...any) {
Print(v...)
Exit(1)
}
func Fatalf(format string, v ...any) {
Printf(format, v...)
Exit(1)
}

25
internal/fmsg/verbose.go Normal file
View File

@ -0,0 +1,25 @@
package fmsg
import "sync/atomic"
var verbose = new(atomic.Bool)
func Verbose() bool {
return verbose.Load()
}
func SetVerbose(v bool) {
verbose.Store(v)
}
func VPrintf(format string, v ...any) {
if verbose.Load() {
Printf(format, v...)
}
}
func VPrintln(v ...any) {
if verbose.Load() {
Println(v...)
}
}

View File

@ -0,0 +1,70 @@
package linux
import (
"io"
"io/fs"
"os/user"
"path"
"strconv"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
// System provides safe access to operating system resources.
type System interface {
// Geteuid provides [os.Geteuid].
Geteuid() int
// LookupEnv provides [os.LookupEnv].
LookupEnv(key string) (string, bool)
// TempDir provides [os.TempDir].
TempDir() string
// LookPath provides [exec.LookPath].
LookPath(file string) (string, error)
// Executable provides [os.Executable].
Executable() (string, error)
// LookupGroup provides [user.LookupGroup].
LookupGroup(name string) (*user.Group, error)
// ReadDir provides [os.ReadDir].
ReadDir(name string) ([]fs.DirEntry, error)
// Stat provides [os.Stat].
Stat(name string) (fs.FileInfo, error)
// Open provides [os.Open]
Open(name string) (fs.File, error)
// Exit provides [os.Exit].
Exit(code int)
// Stdout provides [os.Stdout].
Stdout() io.Writer
// Paths returns a populated [Paths] struct.
Paths() Paths
// Uid invokes fsu and returns target uid.
Uid(aid int) (int, error)
}
// Paths contains environment dependent paths used by fortify.
type Paths struct {
// path to shared directory e.g. /tmp/fortify.%d
SharePath string `json:"share_path"`
// XDG_RUNTIME_DIR value e.g. /run/user/%d
RuntimePath string `json:"runtime_path"`
// application runtime directory e.g. /run/user/%d/fortify
RunDirPath string `json:"run_dir_path"`
}
// CopyPaths is a generic implementation of [System.Paths].
func CopyPaths(os System, v *Paths) {
v.SharePath = path.Join(os.TempDir(), "fortify."+strconv.Itoa(os.Geteuid()))
fmsg.VPrintf("process share directory at %q", v.SharePath)
if r, ok := os.LookupEnv(xdgRuntimeDir); !ok || r == "" || !path.IsAbs(r) {
// fall back to path in share since fortify has no hard XDG dependency
v.RunDirPath = path.Join(v.SharePath, "run")
v.RuntimePath = path.Join(v.RunDirPath, "compat")
} else {
v.RuntimePath = r
v.RunDirPath = path.Join(v.RuntimePath, "fortify")
}
fmsg.VPrintf("runtime directory at %q", v.RunDirPath)
}

88
internal/linux/std.go Normal file
View File

@ -0,0 +1,88 @@
package linux
import (
"io"
"io/fs"
"os"
"os/exec"
"os/user"
"strconv"
"sync"
"git.gensokyo.uk/security/fortify/internal"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
// Std implements System using the standard library.
type Std struct {
paths Paths
pathsOnce sync.Once
uidOnce sync.Once
uidCopy map[int]struct {
uid int
err error
}
uidMu sync.RWMutex
}
func (s *Std) Geteuid() int { return os.Geteuid() }
func (s *Std) LookupEnv(key string) (string, bool) { return os.LookupEnv(key) }
func (s *Std) TempDir() string { return os.TempDir() }
func (s *Std) LookPath(file string) (string, error) { return exec.LookPath(file) }
func (s *Std) Executable() (string, error) { return os.Executable() }
func (s *Std) LookupGroup(name string) (*user.Group, error) { return user.LookupGroup(name) }
func (s *Std) ReadDir(name string) ([]os.DirEntry, error) { return os.ReadDir(name) }
func (s *Std) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) }
func (s *Std) Open(name string) (fs.File, error) { return os.Open(name) }
func (s *Std) Exit(code int) { fmsg.Exit(code) }
func (s *Std) Stdout() io.Writer { return os.Stdout }
const xdgRuntimeDir = "XDG_RUNTIME_DIR"
func (s *Std) Paths() Paths {
s.pathsOnce.Do(func() { CopyPaths(s, &s.paths) })
return s.paths
}
func (s *Std) Uid(aid int) (int, error) {
s.uidOnce.Do(func() {
s.uidCopy = make(map[int]struct {
uid int
err error
})
})
s.uidMu.RLock()
if u, ok := s.uidCopy[aid]; ok {
s.uidMu.RUnlock()
return u.uid, u.err
}
s.uidMu.RUnlock()
s.uidMu.Lock()
defer s.uidMu.Unlock()
u := struct {
uid int
err error
}{}
defer func() { s.uidCopy[aid] = u }()
u.uid = -1
if fsu, ok := internal.Check(internal.Fsu); !ok {
fmsg.Fatal("invalid fsu path, this copy of fshim is not compiled correctly")
panic("unreachable")
} else {
cmd := exec.Command(fsu)
cmd.Path = fsu
cmd.Stderr = os.Stderr // pass through fatal messages
cmd.Env = []string{"FORTIFY_APP_ID=" + strconv.Itoa(aid)}
cmd.Dir = "/"
var p []byte
if p, u.err = cmd.Output(); u.err == nil {
u.uid, u.err = strconv.Atoi(string(p))
}
return u.uid, u.err
}
}

12
internal/path.go Normal file
View File

@ -0,0 +1,12 @@
package internal
import "path"
var (
Fsu = compPoison
Finit = compPoison
)
func Path(p string) (string, bool) {
return p, p != compPoison && p != "" && path.IsAbs(p)
}

20
internal/prctl.go Normal file
View File

@ -0,0 +1,20 @@
package internal
import "syscall"
func PR_SET_DUMPABLE__SUID_DUMP_DISABLE() error {
// linux/sched/coredump.h
if _, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_DUMPABLE, 0, 0); errno != 0 {
return errno
}
return nil
}
func PR_SET_PDEATHSIG__SIGKILL() error {
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGKILL), 0); errno != 0 {
return errno
}
return nil
}

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)
}

13
internal/proc/files.go Normal file
View File

@ -0,0 +1,13 @@
package proc
import (
"os"
"os/exec"
)
func ExtraFile(cmd *exec.Cmd, f *os.File) (fd uintptr) {
// ExtraFiles: If non-nil, entry i becomes file descriptor 3+i.
fd = uintptr(3 + len(cmd.ExtraFiles))
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
return
}

292
internal/state/multi.go Normal file
View 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
}

View 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()))
}

118
internal/state/print.go Normal file
View File

@ -0,0 +1,118 @@
package state
import (
"fmt"
"os"
"strings"
"text/tabwriter"
"time"
"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 aids, err := s.List(); err != nil {
fmsg.Fatal("cannot list store:", err)
} else {
for _, aid := range aids {
// print states belonging to this store
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 *multiStore) mustPrintLauncherState(aid int, w **tabwriter.Writer, now time.Time) {
var innerErr error
if ok, err := s.Do(aid, func(c Cursor) {
innerErr = func() error {
// read launcher states
states, err := c.Load()
if err != nil {
return err
}
// initialise tabwriter if nil
if *w == nil {
*w = tabwriter.NewWriter(os.Stdout, 0, 1, 4, ' ', 0)
// write header when initialising
if !fmsg.Verbose() {
_, _ = fmt.Fprintln(*w, "\tPID\tApp\tUptime\tEnablements\tCommand")
} else {
// argv is emitted in body when verbose
_, _ = fmt.Fprintln(*w, "\tPID\tApp\tArgv")
}
}
// print each state
for _, state := range states {
// skip nil states
if state == nil {
_, _ = fmt.Fprintln(*w, "\tnil state entry")
continue
}
// build enablements and command string
var (
ets *strings.Builder
cs = "(No command information)"
)
// check if enablements are provided
if state.Config != nil {
ets = new(strings.Builder)
// append enablement strings in order
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ {
if state.Config.Confinement.Enablements.Has(i) {
ets.WriteString(", " + i.String())
}
}
cs = fmt.Sprintf("%q", state.Config.Command)
}
if ets != nil {
// prevent an empty string
if ets.Len() == 0 {
ets.WriteString("(No enablements)")
}
} else {
ets = new(strings.Builder)
ets.WriteString("(No confinement information)")
}
if !fmsg.Verbose() {
_, _ = fmt.Fprintf(*w, "\t%d\t%d\t%s\t%s\t%s\n",
state.PID, aid, now.Sub(state.Time).Round(time.Second).String(), strings.TrimPrefix(ets.String(), ", "), cs)
} else {
// emit argv instead when verbose
_, _ = 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 app %d: %v", aid, err)
if !ok {
fmsg.Fatal("store faulted before printing")
}
}
if innerErr != nil {
fmsg.Fatalf("cannot print launcher state of app %d: %s", aid, innerErr)
}
}

44
internal/state/state.go Normal file
View File

@ -0,0 +1,44 @@
package state
import (
"time"
"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.
// 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
}
// Cursor provides access to the store
type Cursor interface {
Save(state *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 `json:"pid"`
// sealed app configuration
Config *fst.Config `json:"config"`
// process start time
Time time.Time
}

View 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()
}

70
internal/system/acl.go Normal file
View File

@ -0,0 +1,70 @@
package system
import (
"fmt"
"slices"
"git.gensokyo.uk/security/fortify/acl"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
// UpdatePerm appends an ephemeral acl update Op.
func (sys *I) UpdatePerm(path string, perms ...acl.Perm) *I {
sys.UpdatePermType(Process, path, perms...)
return sys
}
// UpdatePermType appends an acl update Op.
func (sys *I) UpdatePermType(et Enablement, path string, perms ...acl.Perm) *I {
sys.lock.Lock()
defer sys.lock.Unlock()
sys.ops = append(sys.ops, &ACL{et, path, perms})
return sys
}
type ACL struct {
et Enablement
path string
perms acl.Perms
}
func (a *ACL) Type() Enablement {
return a.et
}
func (a *ACL) apply(sys *I) error {
fmsg.VPrintln("applying ACL", a)
return fmsg.WrapErrorSuffix(acl.UpdatePerm(a.path, sys.uid, a.perms...),
fmt.Sprintf("cannot apply ACL entry to %q:", a.path))
}
func (a *ACL) revert(sys *I, ec *Criteria) error {
if ec.hasType(a) {
fmsg.VPrintln("stripping ACL", a)
return fmsg.WrapErrorSuffix(acl.UpdatePerm(a.path, sys.uid),
fmt.Sprintf("cannot strip ACL entry from %q:", a.path))
} else {
fmsg.VPrintln("skipping ACL", a)
return nil
}
}
func (a *ACL) Is(o Op) bool {
a0, ok := o.(*ACL)
return ok && a0 != nil &&
a.et == a0.et &&
a.path == a0.path &&
slices.Equal(a.perms, a0.perms)
}
func (a *ACL) Path() string {
return a.path
}
func (a *ACL) String() string {
return fmt.Sprintf("%s type: %s path: %q",
a.perms, TypeString(a.et), a.path)
}

View File

@ -0,0 +1,90 @@
package system
import (
"testing"
"git.gensokyo.uk/security/fortify/acl"
)
func TestUpdatePerm(t *testing.T) {
testCases := []struct {
path string
perms []acl.Perm
}{
{"/run/user/1971/fortify", []acl.Perm{acl.Execute}},
{"/tmp/fortify.1971/tmpdir/150", []acl.Perm{acl.Read, acl.Write, acl.Execute}},
}
for _, tc := range testCases {
t.Run(tc.path+permSubTestSuffix(tc.perms), func(t *testing.T) {
sys := New(150)
sys.UpdatePerm(tc.path, tc.perms...)
(&tcOp{Process, tc.path}).test(t, sys.ops, []Op{&ACL{Process, tc.path, tc.perms}}, "UpdatePerm")
})
}
}
func TestUpdatePermType(t *testing.T) {
testCases := []struct {
perms []acl.Perm
tcOp
}{
{[]acl.Perm{acl.Execute}, tcOp{User, "/tmp/fortify.1971/tmpdir"}},
{[]acl.Perm{acl.Read, acl.Write, acl.Execute}, tcOp{User, "/tmp/fortify.1971/tmpdir/150"}},
{[]acl.Perm{acl.Execute}, tcOp{Process, "/run/user/1971/fortify/fcb8a12f7c482d183ade8288c3de78b5"}},
{[]acl.Perm{acl.Read}, tcOp{Process, "/tmp/fortify.1971/fcb8a12f7c482d183ade8288c3de78b5/passwd"}},
{[]acl.Perm{acl.Read}, tcOp{Process, "/tmp/fortify.1971/fcb8a12f7c482d183ade8288c3de78b5/group"}},
{[]acl.Perm{acl.Read, acl.Write, acl.Execute}, tcOp{EWayland, "/run/user/1971/wayland-0"}},
}
for _, tc := range testCases {
t.Run(tc.path+"_"+TypeString(tc.et)+permSubTestSuffix(tc.perms), func(t *testing.T) {
sys := New(150)
sys.UpdatePermType(tc.et, tc.path, tc.perms...)
tc.test(t, sys.ops, []Op{&ACL{tc.et, tc.path, tc.perms}}, "UpdatePermType")
})
}
}
func TestACL_String(t *testing.T) {
testCases := []struct {
want string
et Enablement
perms []acl.Perm
}{
{`--- type: Process path: "/nonexistent"`, Process, []acl.Perm{}},
{`r-- type: User path: "/nonexistent"`, User, []acl.Perm{acl.Read}},
{`-w- type: Wayland path: "/nonexistent"`, EWayland, []acl.Perm{acl.Write}},
{`--x type: X11 path: "/nonexistent"`, EX11, []acl.Perm{acl.Execute}},
{`rw- type: D-Bus path: "/nonexistent"`, EDBus, []acl.Perm{acl.Read, acl.Write}},
{`r-x type: PulseAudio path: "/nonexistent"`, EPulse, []acl.Perm{acl.Read, acl.Execute}},
{`rwx type: User path: "/nonexistent"`, User, []acl.Perm{acl.Read, acl.Write, acl.Execute}},
{`rwx type: Process path: "/nonexistent"`, Process, []acl.Perm{acl.Read, acl.Write, acl.Write, acl.Execute}},
}
for _, tc := range testCases {
t.Run(tc.want, func(t *testing.T) {
a := &ACL{et: tc.et, perms: tc.perms, path: "/nonexistent"}
if got := a.String(); got != tc.want {
t.Errorf("String() = %v, want %v",
got, tc.want)
}
})
}
}
func permSubTestSuffix(perms []acl.Perm) (suffix string) {
for _, perm := range perms {
switch perm {
case acl.Read:
suffix += "_read"
case acl.Write:
suffix += "_write"
case acl.Execute:
suffix += "_execute"
default:
panic("unreachable")
}
}
return
}

202
internal/system/dbus.go Normal file
View File

@ -0,0 +1,202 @@
package system
import (
"bytes"
"errors"
"os"
"strings"
"sync"
"git.gensokyo.uk/security/fortify/dbus"
"git.gensokyo.uk/security/fortify/internal/fmsg"
)
var (
ErrDBusConfig = errors.New("dbus config not supplied")
)
func (sys *I) MustProxyDBus(sessionPath string, session *dbus.Config, systemPath string, system *dbus.Config) *I {
if _, err := sys.ProxyDBus(session, system, sessionPath, systemPath); err != nil {
panic(err.Error())
} else {
return sys
}
}
func (sys *I) ProxyDBus(session, system *dbus.Config, sessionPath, systemPath string) (func(f func(msgbuf []string)), error) {
d := new(DBus)
// used by waiting goroutine to notify process exit
d.done = make(chan struct{})
// session bus is mandatory
if session == nil {
return nil, fmsg.WrapError(ErrDBusConfig,
"attempted to seal message bus proxy without session bus config")
}
// system bus is optional
d.system = system == nil
// upstream address, downstream socket path
var sessionBus, systemBus [2]string
// resolve upstream bus addresses
sessionBus[0], systemBus[0] = dbus.Address()
// set paths from caller
sessionBus[1], systemBus[1] = sessionPath, systemPath
// create proxy instance
d.proxy = dbus.New(sessionBus, systemBus)
defer func() {
if fmsg.Verbose() && d.proxy.Sealed() {
fmsg.VPrintln("sealed session proxy", session.Args(sessionBus))
if system != nil {
fmsg.VPrintln("sealed system proxy", system.Args(systemBus))
}
fmsg.VPrintln("message bus proxy final args:", d.proxy)
}
}()
// queue operation
sys.ops = append(sys.ops, d)
// seal dbus proxy
d.out = &scanToFmsg{msg: new(strings.Builder)}
return d.out.F, fmsg.WrapErrorSuffix(d.proxy.Seal(session, system),
"cannot seal message bus proxy:")
}
type DBus struct {
proxy *dbus.Proxy
out *scanToFmsg
// whether system bus proxy is enabled
system bool
// notification from goroutine waiting for dbus.Proxy
done chan struct{}
}
func (d *DBus) Type() Enablement {
return Process
}
func (d *DBus) apply(_ *I) error {
fmsg.VPrintf("session bus proxy on %q for upstream %q", d.proxy.Session()[1], d.proxy.Session()[0])
if d.system {
fmsg.VPrintf("system bus proxy on %q for upstream %q", d.proxy.System()[1], d.proxy.System()[0])
}
// ready channel passed to dbus package
ready := make(chan error, 1)
// background dbus proxy start
if err := d.proxy.Start(ready, d.out, true); err != nil {
return fmsg.WrapErrorSuffix(err,
"cannot start message bus proxy:")
}
fmsg.VPrintln("starting message bus proxy:", d.proxy)
if fmsg.Verbose() { // save the extra bwrap arg build when verbose logging is off
fmsg.VPrintln("message bus proxy bwrap args:", d.proxy.Bwrap())
}
// background wait for proxy instance and notify completion
go func() {
if err := d.proxy.Wait(); err != nil {
fmsg.Println("message bus proxy exited with error:", err)
go func() { ready <- err }()
} else {
fmsg.VPrintln("message bus proxy exit")
}
// ensure socket removal so ephemeral directory is empty at revert
if err := os.Remove(d.proxy.Session()[1]); err != nil && !errors.Is(err, os.ErrNotExist) {
fmsg.Println("cannot remove dangling session bus socket:", err)
}
if d.system {
if err := os.Remove(d.proxy.System()[1]); err != nil && !errors.Is(err, os.ErrNotExist) {
fmsg.Println("cannot remove dangling system bus socket:", err)
}
}
// notify proxy completion
close(d.done)
}()
// ready is not nil if the proxy process faulted
if err := <-ready; err != nil {
// note that err here is either an I/O error or a predetermined unexpected behaviour error
return fmsg.WrapErrorSuffix(err,
"message bus proxy fault after start:")
}
fmsg.VPrintln("message bus proxy ready")
return nil
}
func (d *DBus) revert(_ *I, _ *Criteria) error {
// criteria ignored here since dbus is always process-scoped
fmsg.VPrintln("terminating message bus proxy")
if err := d.proxy.Close(); err != nil {
if errors.Is(err, os.ErrClosed) {
return fmsg.WrapError(err,
"message bus proxy already closed")
} else {
return fmsg.WrapErrorSuffix(err,
"cannot stop message bus proxy:")
}
}
// block until proxy wait returns
<-d.done
return nil
}
func (d *DBus) Is(o Op) bool {
d0, ok := o.(*DBus)
return ok && d0 != nil &&
((d.proxy == nil && d0.proxy == nil) ||
(d.proxy != nil && d0.proxy != nil && d.proxy.String() == d0.proxy.String()))
}
func (d *DBus) Path() string {
return "(dbus proxy)"
}
func (d *DBus) String() string {
return d.proxy.String()
}
type scanToFmsg struct {
msg *strings.Builder
msgbuf []string
mu sync.RWMutex
}
func (s *scanToFmsg) Write(p []byte) (n int, err error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.write(p, 0)
}
func (s *scanToFmsg) write(p []byte, a int) (int, error) {
if i := bytes.IndexByte(p, '\n'); i == -1 {
n, _ := s.msg.Write(p)
return a + n, nil
} else {
n, _ := s.msg.Write(p[:i])
s.msgbuf = append(s.msgbuf, s.msg.String())
s.msg.Reset()
return s.write(p[i+1:], a+n+1)
}
}
func (s *scanToFmsg) F(f func(msgbuf []string)) {
s.mu.RLock()
f(s.msgbuf)
s.mu.RUnlock()
}

View File

@ -0,0 +1,49 @@
package system
type (
// Enablement represents an optional system resource
Enablement uint8
// Enablements represents optional system resources to share
Enablements uint64
)
const (
EWayland Enablement = iota
EX11
EDBus
EPulse
)
var enablementString = [...]string{
EWayland: "Wayland",
EX11: "X11",
EDBus: "D-Bus",
EPulse: "PulseAudio",
}
const ELen = len(enablementString)
func (e Enablement) String() string {
if int(e) >= ELen {
return "<invalid enablement>"
}
return enablementString[e]
}
func (e Enablement) Mask() Enablements {
return 1 << e
}
// Has returns whether a feature is enabled
func (es *Enablements) Has(e Enablement) bool {
return *es&e.Mask() != 0
}
// Set enables a feature
func (es *Enablements) Set(e Enablement) {
if es.Has(e) {
panic("enablement " + e.String() + " set twice")
}
*es |= e.Mask()
}

Some files were not shown because too many files have changed in this diff Show More