Compare commits
302 Commits
9d9a165379
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
cb513bb1cd
|
|||
|
f7bd28118c
|
|||
|
940ee00ffe
|
|||
|
b43d104680
|
|||
|
ddf48a6c22
|
|||
|
a0f499e30a
|
|||
|
d6b07f12ff
|
|||
|
65fe09caf9
|
|||
|
a1e5f020f4
|
|||
|
bd3fa53a55
|
|||
|
625632c593
|
|||
|
e71ae3b8c5
|
|||
|
9d7a19d162
|
|||
|
6ba19a7ba5
|
|||
|
749a2779f5
|
|||
|
e574042d76
|
|||
|
2b44493e8a
|
|||
|
c30dd4e630
|
|||
|
d90da1c8f5
|
|||
|
5853d7700f
|
|||
|
d5c7523726
|
|||
|
ddfcc51b91
|
|||
|
8ebedbd88a
|
|||
|
84e8142a2d
|
|||
|
2c7b7ad845
|
|||
|
72c2b66fc0
|
|||
|
356b42a406
|
|||
|
d9b6d48e7c
|
|||
|
087959e81b
|
|||
|
e6967b8bbb
|
|||
|
d2f9a9b83b
|
|||
|
1b5ecd9eaf
|
|||
|
82561d62b6
|
|||
|
eec021cc4b
|
|||
|
a1d98823f8
|
|||
|
255b77d91d
|
|||
|
f84ec5a3f8
|
|||
|
eb22a8bcc1
|
|||
|
31aef905fa
|
|||
|
a6887f7253
|
|||
|
69bd581af7
|
|||
|
26b7afc890
|
|||
|
d5532aade0
|
|||
|
0c5409aec7
|
|||
|
1a8840bebc
|
|||
|
1fb453dffe
|
|||
|
e03d702d08
|
|||
|
241dc964a6
|
|||
|
8ef71e14d5
|
|||
|
972f4006f0
|
|||
|
9a8a047908
|
|||
|
863bf69ad3
|
|||
|
0e957cc9c1
|
|||
|
aa454b158f
|
|||
|
7007bd6a1c
|
|||
|
00efc95ee7
|
|||
|
b380bb248c
|
|||
|
87e008d56d
|
|||
|
3992073212
|
|||
|
ef80b19f2f
|
|||
|
717771ae80
|
|||
|
bf5772bd8a
|
|||
|
9a7c81a44e
|
|||
|
b7e991de5b
|
|||
|
6c1205106d
|
|||
|
2ffca6984a
|
|||
|
dde2516304
|
|||
|
f30a439bcd
|
|||
|
008e9e7fc5
|
|||
|
23aefcd759
|
|||
|
cb8b886446
|
|||
|
5979d8b1e0
|
|||
|
e587112e63
|
|||
|
d6cf736abf
|
|||
|
15011c4173
|
|||
|
31b7ddd122
|
|||
|
c460892cbd
|
|||
|
6309469e93
|
|||
|
0d7c1a9a43
|
|||
|
ae6f5ede19
|
|||
|
807d511c8b
|
|||
|
2f4f21fb18
|
|||
|
9967909460
|
|||
|
c806f43881
|
|||
|
584405f7cc
|
|||
|
50127ed5f9
|
|||
|
b5eff27c40
|
|||
|
74ba183256
|
|||
|
f885dede9b
|
|||
|
e9a7cd526f
|
|||
|
12be7bc78e
|
|||
|
0ba8be659f
|
|||
|
022242a84a
|
|||
|
8aeb06f53c
|
|||
|
4036da3b5c
|
|||
|
986105958c
|
|||
|
ecdd4d8202
|
|||
|
bdee0c3921
|
|||
|
48f634d046
|
|||
|
2a46f5bb12
|
|||
|
7f2c0af5ad
|
|||
|
297b444dfb
|
|||
|
89a05909a4
|
|||
|
f772940768
|
|||
|
8886c40974
|
|||
|
8b62e08b44
|
|||
|
72c59f9229
|
|||
|
ff3cfbb437
|
|||
|
c13eb70d7d
|
|||
|
389402f955
|
|||
|
660a2898dc
|
|||
|
faf59e12c0
|
|||
|
d97a03c7c6
|
|||
|
a102178019
|
|||
|
e400862a12
|
|||
|
184e9db2b2
|
|||
|
605d018be2
|
|||
|
78aaae7ee0
|
|||
|
5c82f1ed3e
|
|||
|
f8502c3ece
|
|||
|
996b42634d
|
|||
|
300571af47
|
|||
|
32c90ef4e7
|
|||
|
2a4e2724a3
|
|||
|
d613257841
|
|||
|
18644d90be
|
|||
|
52fcc48ac1
|
|||
|
8b69bcd215
|
|||
|
2dd49c437c
|
|||
|
92852d8235
|
|||
|
371dd5b938
|
|||
|
4836d570ae
|
|||
|
985f9442e6
|
|||
|
67eb28466d
|
|||
|
c326c3f97d
|
|||
|
971c79bb80
|
|||
|
f86d868274
|
|||
|
33940265a6
|
|||
|
b39f3aeb59
|
|||
|
61dbfeffe7
|
|||
|
532feb4bfa
|
|||
|
ec5e91b8c9
|
|||
|
ee51320abf
|
|||
|
5c4058d5ac
|
|||
|
e732dca762
|
|||
|
a9adcd914b
|
|||
|
3dd4ff29c8
|
|||
|
61d86c5e10
|
|||
|
d097eaa28f
|
|||
|
ad3576c164
|
|||
|
b989a4601a
|
|||
|
a11237b158
|
|||
|
40f00d570e
|
|||
|
0eb1bc6301
|
|||
|
1eb837eab8
|
|||
|
0a4e633db2
|
|||
|
e8809125d4
|
|||
|
806ce18c0a
|
|||
|
b71d2bf534
|
|||
|
46059b1840
|
|||
|
d2c329bcea
|
|||
|
2d379b5a38
|
|||
|
75e0c5d406
|
|||
|
770b37ae16
|
|||
|
c638193268
|
|||
|
8c3a817881
|
|||
|
e2fce321c1
|
|||
|
241702ae3a
|
|||
|
d21d9c5b1d
|
|||
|
a70daf2250
|
|||
|
632b18addd
|
|||
|
a57a7a6a16
|
|||
|
5098b12e4a
|
|||
|
9ddf5794dd
|
|||
|
b74a08dda9
|
|||
|
1b9408864f
|
|||
|
cc89dbdf63
|
|||
|
228f3301f2
|
|||
|
07181138e5
|
|||
|
816b372f14
|
|||
|
d7eddd54a2
|
|||
|
7c063833e0
|
|||
|
af3619d440
|
|||
|
528674cb6e
|
|||
|
70c9757e26
|
|||
|
c83a7e2efc
|
|||
|
904208b87f
|
|||
|
007b52d81f
|
|||
|
3385538142
|
|||
|
24618ab9a1
|
|||
|
9ce4706a07
|
|||
|
9a1f8e129f
|
|||
|
ee10860357
|
|||
|
44277dc0f1
|
|||
|
bc54db54d2
|
|||
|
bf07b7cd9e
|
|||
|
5d3c8dcc92
|
|||
|
48feca800f
|
|||
|
42de09e896
|
|||
|
1576fea8a3
|
|||
|
ae522ab364
|
|||
|
273d97af85
|
|||
|
891316d924
|
|||
|
9f5dad1998
|
|||
|
6e7ddb2d2e
|
|||
|
bac4e67867
|
|||
|
4230281194
|
|||
|
e64e7608ca
|
|||
|
10a21ce3ef
|
|||
|
0f1f0e4364
|
|||
|
f9bf20a3c7
|
|||
|
73c1a83032
|
|||
|
f443d315ad
|
|||
|
9e18d1de77
|
|||
|
2647a71be1
|
|||
|
7c60a4d8e8
|
|||
|
4bb5d9780f
|
|||
|
f41fd94628
|
|||
|
94895bbacb
|
|||
|
f332200ca4
|
|||
|
2eff470091
|
|||
|
a092b042ab
|
|||
|
e94b09d337
|
|||
|
5d9e669d97
|
|||
|
f1002157a5
|
|||
|
4133b555ba
|
|||
|
9b1a60b5c9
|
|||
|
beb3918809
|
|||
|
2871426df2
|
|||
|
e048f31baa
|
|||
|
6af8b8859f
|
|||
|
f38ba7e923
|
|||
|
d22145a392
|
|||
|
29c3f8becb
|
|||
|
be16970e77
|
|||
|
df266527f1
|
|||
|
c8ed7aae6e
|
|||
|
61e58aa14d
|
|||
|
9e15898c8f
|
|||
|
f7bd6a5a41
|
|||
|
ea853e21d9
|
|||
|
0bd9b9e8fe
|
|||
|
39e32799b3
|
|||
|
9953768de5
|
|||
|
0d3652b793
|
|||
|
d8e9d71f87
|
|||
|
558974b996
|
|||
|
4de4049713
|
|||
|
2d4cabe786
|
|||
|
80f9b62d25
|
|||
|
673b648bd3
|
|||
|
45ad788c6d
|
|||
|
56539d8db5
|
|||
|
840ceb615a
|
|||
|
741d011543
|
|||
|
d050b3de25
|
|||
|
5de28800ad
|
|||
|
8e50293ab7
|
|||
|
12c6d66bfd
|
|||
|
d7d2bd33ed
|
|||
|
c21a4cff14
|
|||
|
4fa38d6063
|
|||
|
6d4ac3d9fd
|
|||
|
a5d2f040fb
|
|||
|
c62689e17f
|
|||
|
39dc8e7bd8
|
|||
|
5a732d153e
|
|||
|
b4549c72be
|
|||
|
1818dc3a4c
|
|||
|
65094b63cd
|
|||
|
f0a082ec84
|
|||
|
751aa350ee
|
|||
|
e6cd2bb2a8
|
|||
|
0fb72e5d99
|
|||
|
71135f339a
|
|||
|
b6af8caffe
|
|||
|
e1a3549ea0
|
|||
|
8bf162820b
|
|||
|
dccb366608
|
|||
|
83c8f0488b
|
|||
|
478b27922c
|
|||
|
ba1498cd18
|
|||
|
eda4d612c2
|
|||
|
2e7e160683
|
|||
|
79957f8ea7
|
|||
|
7e52463445
|
|||
|
89970f5197
|
|||
|
35037705a9
|
|||
|
647c6ea21b
|
|||
|
416d93e880
|
|||
|
312753924b
|
|||
|
54308f79d2
|
|||
|
dfa3217037
|
|||
|
8000a2febb
|
|||
|
7bd48d3489
|
|||
|
b5eaeac11a
|
|||
|
a9986aab6a
|
|||
|
ff30a5ab5d
|
|||
|
eb0c16dd8c
|
|||
|
4fa1e97026
|
|||
|
64b6dc41ba
|
|||
|
c64b8163e7
|
@@ -20,5 +20,5 @@ jobs:
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: |-
|
||||
result/fortify-**
|
||||
result/hakurei-**
|
||||
api_key: '${{secrets.RELEASE_TOKEN}}'
|
||||
|
||||
@@ -5,25 +5,107 @@ on:
|
||||
- pull_request
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run NixOS test
|
||||
hakurei:
|
||||
name: Hakurei
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
nix --print-build-logs --experimental-features 'nix-command flakes' flake check
|
||||
nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.nixos-tests
|
||||
- name: Run NixOS test
|
||||
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.hakurei
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "nixos-vm-output"
|
||||
name: "hakurei-vm-output"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
race:
|
||||
name: Hakurei (race detector)
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run NixOS test
|
||||
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.race
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "hakurei-race-vm-output"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
sandbox:
|
||||
name: Sandbox
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run NixOS test
|
||||
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.sandbox
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "sandbox-vm-output"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
sandbox-race:
|
||||
name: Sandbox (race detector)
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run NixOS test
|
||||
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.sandbox-race
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "sandbox-race-vm-output"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
planterette:
|
||||
name: Planterette
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run NixOS test
|
||||
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.planterette
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "planterette-vm-output"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
check:
|
||||
name: Flake checks
|
||||
needs:
|
||||
- hakurei
|
||||
- race
|
||||
- sandbox
|
||||
- sandbox-race
|
||||
- planterette
|
||||
runs-on: nix
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run checks
|
||||
run: nix --print-build-logs --experimental-features 'nix-command flakes' flake check
|
||||
|
||||
dist:
|
||||
name: Create distribution
|
||||
runs-on: nix
|
||||
@@ -34,15 +116,15 @@ jobs:
|
||||
- name: Build for test
|
||||
id: build-test
|
||||
run: >-
|
||||
export FORTIFY_REV="$(git rev-parse --short HEAD)" &&
|
||||
sed -i.old 's/version = /version = "0.0.0-'$FORTIFY_REV'"; # version = /' package.nix &&
|
||||
export HAKUREI_REV="$(git rev-parse --short HEAD)" &&
|
||||
sed -i.old 's/version = /version = "0.0.0-'$HAKUREI_REV'"; # version = /' package.nix &&
|
||||
nix build --print-out-paths --print-build-logs .#dist &&
|
||||
mv package.nix.old package.nix &&
|
||||
echo "rev=$FORTIFY_REV" >> $GITHUB_OUTPUT
|
||||
echo "rev=$HAKUREI_REV" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Upload test build
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "fortify-${{ steps.build-test.outputs.rev }}"
|
||||
name: "hakurei-${{ steps.build-test.outputs.rev }}"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
|
||||
1
.github/workflows/README
vendored
Normal file
1
.github/workflows/README
vendored
Normal file
@@ -0,0 +1 @@
|
||||
This port is solely for releasing to the github mirror and serves no purpose during development.
|
||||
46
.github/workflows/release.yml
vendored
Normal file
46
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Create release
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Nix
|
||||
uses: nixbuild/nix-quick-install-action@v32
|
||||
with:
|
||||
nix_conf: |
|
||||
keep-env-derivations = true
|
||||
keep-outputs = true
|
||||
|
||||
- name: Restore and cache Nix store
|
||||
uses: nix-community/cache-nix-action@v6
|
||||
with:
|
||||
primary-key: build-${{ runner.os }}-${{ hashFiles('**/*.nix') }}
|
||||
restore-prefixes-first-match: build-${{ runner.os }}-
|
||||
gc-max-store-size-linux: 1G
|
||||
purge: true
|
||||
purge-prefixes: build-${{ runner.os }}-
|
||||
purge-created: 60
|
||||
purge-primary-key: never
|
||||
|
||||
- name: Build for release
|
||||
run: nix build --print-out-paths --print-build-logs .#dist
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |-
|
||||
result/hakurei-**
|
||||
48
.github/workflows/test.yml
vendored
Normal file
48
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
- push
|
||||
|
||||
jobs:
|
||||
dist:
|
||||
name: Create distribution
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Nix
|
||||
uses: nixbuild/nix-quick-install-action@v32
|
||||
with:
|
||||
nix_conf: |
|
||||
keep-env-derivations = true
|
||||
keep-outputs = true
|
||||
|
||||
- name: Restore and cache Nix store
|
||||
uses: nix-community/cache-nix-action@v6
|
||||
with:
|
||||
primary-key: build-${{ runner.os }}-${{ hashFiles('**/*.nix') }}
|
||||
restore-prefixes-first-match: build-${{ runner.os }}-
|
||||
gc-max-store-size-linux: 1G
|
||||
purge: true
|
||||
purge-prefixes: build-${{ runner.os }}-
|
||||
purge-created: 60
|
||||
purge-primary-key: never
|
||||
|
||||
- name: Build for test
|
||||
id: build-test
|
||||
run: >-
|
||||
export HAKUREI_REV="$(git rev-parse --short HEAD)" &&
|
||||
sed -i.old 's/version = /version = "0.0.0-'$HAKUREI_REV'"; # version = /' package.nix &&
|
||||
nix build --print-out-paths --print-build-logs .#dist &&
|
||||
mv package.nix.old package.nix &&
|
||||
echo "rev=$HAKUREI_REV" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Upload test build
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: "hakurei-${{ steps.build-test.outputs.rev }}"
|
||||
path: result/*
|
||||
retention-days: 1
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -5,7 +5,7 @@
|
||||
*.so
|
||||
*.dylib
|
||||
*.pkg
|
||||
/fortify
|
||||
/hakurei
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
@@ -26,7 +26,7 @@ go.work.sum
|
||||
.vscode
|
||||
|
||||
# go generate
|
||||
security-context-v1-protocol.*
|
||||
/cmd/hakurei/LICENSE
|
||||
|
||||
# release
|
||||
/dist/fortify-*
|
||||
/dist/hakurei-*
|
||||
2
LICENSE
2
LICENSE
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2024 Ophestra Umiker
|
||||
Copyright (c) 2024-2025 Ophestra
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
109
README.md
109
README.md
@@ -1,77 +1,83 @@
|
||||
Fortify
|
||||
=======
|
||||
<p align="center">
|
||||
<a href="https://git.gensokyo.uk/security/hakurei">
|
||||
<picture>
|
||||
<img src="https://basement.gensokyo.uk/images/yukari1.png" width="200px" alt="Yukari">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
[](https://pkg.go.dev/git.gensokyo.uk/security/fortify)
|
||||
[](https://goreportcard.com/report/git.gensokyo.uk/security/fortify)
|
||||
<p align="center">
|
||||
<a href="https://pkg.go.dev/hakurei.app"><img src="https://pkg.go.dev/badge/hakurei.app.svg" alt="Go Reference" /></a>
|
||||
<a href="https://git.gensokyo.uk/security/hakurei/actions"><img src="https://git.gensokyo.uk/security/hakurei/actions/workflows/test.yml/badge.svg?branch=staging&style=flat-square" alt="Gitea Workflow Status" /></a>
|
||||
<br/>
|
||||
<a href="https://git.gensokyo.uk/security/hakurei/releases"><img src="https://img.shields.io/gitea/v/release/security/hakurei?gitea_url=https%3A%2F%2Fgit.gensokyo.uk&color=purple" alt="Release" /></a>
|
||||
<a href="https://goreportcard.com/report/hakurei.app"><img src="https://goreportcard.com/badge/hakurei.app" alt="Go Report Card" /></a>
|
||||
<a href="https://hakurei.app"><img src="https://img.shields.io/website?url=https%3A%2F%2Fhakurei.app" alt="Website" /></a>
|
||||
</p>
|
||||
|
||||
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.
|
||||
Hakurei is a tool for running sandboxed graphical applications as dedicated subordinate users on the Linux kernel.
|
||||
It also implements [planterette (WIP)](cmd/planterette), a self-contained Android-like package manager with modern security features.
|
||||
|
||||
Why would you want this?
|
||||
## NixOS Module usage
|
||||
|
||||
- It protects the desktop environment from applications.
|
||||
|
||||
- It protects applications from each other.
|
||||
|
||||
- It provides UID isolation on top of the standard application sandbox.
|
||||
|
||||
If you have a flakes-enabled nix environment, you can try out the tool by running:
|
||||
|
||||
```shell
|
||||
nix run git+https://git.gensokyo.uk/security/fortify -- help
|
||||
```
|
||||
|
||||
## Module usage
|
||||
|
||||
The NixOS module currently requires home-manager to function correctly.
|
||||
|
||||
Full module documentation can be found [here](options.md).
|
||||
The NixOS module currently requires home-manager to configure subordinate users. Full module documentation can be found [here](options.md).
|
||||
|
||||
To use the module, import it into your configuration with
|
||||
|
||||
```nix
|
||||
{
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
|
||||
|
||||
fortify = {
|
||||
url = "git+https://git.gensokyo.uk/security/fortify";
|
||||
hakurei = {
|
||||
url = "git+https://git.gensokyo.uk/security/hakurei";
|
||||
|
||||
# Optional but recommended to limit the size of your system closure.
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, fortify, ... }:
|
||||
outputs = { self, nixpkgs, hakurei, ... }:
|
||||
{
|
||||
nixosConfigurations.fortify = nixpkgs.lib.nixosSystem {
|
||||
nixosConfigurations.hakurei = nixpkgs.lib.nixosSystem {
|
||||
system = "x86_64-linux";
|
||||
modules = [
|
||||
fortify.nixosModules.fortify
|
||||
hakurei.nixosModules.hakurei
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
This adds the `environment.fortify` option:
|
||||
This adds the `environment.hakurei` option:
|
||||
|
||||
```nix
|
||||
{ pkgs, ... }:
|
||||
|
||||
{
|
||||
environment.fortify = {
|
||||
environment.hakurei = {
|
||||
enable = true;
|
||||
stateDir = "/var/lib/persist/module/fortify";
|
||||
stateDir = "/var/lib/hakurei";
|
||||
users = {
|
||||
alice = 0;
|
||||
nixos = 10;
|
||||
};
|
||||
|
||||
apps = [
|
||||
commonPaths = [
|
||||
{
|
||||
src = "/sdcard";
|
||||
write = true;
|
||||
}
|
||||
];
|
||||
|
||||
extraHomeConfig = {
|
||||
home.stateVersion = "23.05";
|
||||
};
|
||||
|
||||
apps = {
|
||||
"org.chromium.Chromium" = {
|
||||
name = "chromium";
|
||||
id = "org.chromium.Chromium";
|
||||
identity = 1;
|
||||
packages = [ pkgs.chromium ];
|
||||
userns = true;
|
||||
mapRealUid = true;
|
||||
@@ -104,16 +110,20 @@ This adds the `environment.fortify` option:
|
||||
broadcast = { };
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
};
|
||||
|
||||
"org.claws_mail.Claws-Mail" = {
|
||||
name = "claws-mail";
|
||||
id = "org.claws_mail.Claws-Mail";
|
||||
identity = 2;
|
||||
packages = [ pkgs.claws-mail ];
|
||||
gpu = false;
|
||||
capability.pulse = false;
|
||||
}
|
||||
{
|
||||
};
|
||||
|
||||
"org.weechat" = {
|
||||
name = "weechat";
|
||||
identity = 3;
|
||||
shareUid = true;
|
||||
packages = [ pkgs.weechat ];
|
||||
capability = {
|
||||
wayland = false;
|
||||
@@ -121,10 +131,12 @@ This adds the `environment.fortify` option:
|
||||
dbus = true;
|
||||
pulse = false;
|
||||
};
|
||||
}
|
||||
{
|
||||
};
|
||||
|
||||
"dev.vencord.Vesktop" = {
|
||||
name = "discord";
|
||||
id = "dev.vencord.Vesktop";
|
||||
identity = 3;
|
||||
shareUid = true;
|
||||
packages = [ pkgs.vesktop ];
|
||||
share = pkgs.vesktop;
|
||||
command = "vesktop --ozone-platform-hint=wayland";
|
||||
@@ -142,9 +154,12 @@ This adds the `environment.fortify` option:
|
||||
};
|
||||
system.filter = true;
|
||||
};
|
||||
}
|
||||
{
|
||||
};
|
||||
|
||||
"io.looking-glass" = {
|
||||
name = "looking-glass-client";
|
||||
identity = 4;
|
||||
useCommonPaths = false;
|
||||
groups = [ "plugdev" ];
|
||||
extraPaths = [
|
||||
{
|
||||
@@ -155,8 +170,8 @@ This adds the `environment.fortify` option:
|
||||
extraConfig = {
|
||||
programs.looking-glass-client.enable = true;
|
||||
};
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
#include "acl-update.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <sys/acl.h>
|
||||
#include <acl/libacl.h>
|
||||
|
||||
int f_acl_update_file_by_uid(const char *path_p, uid_t uid, acl_perm_t *perms, size_t plen) {
|
||||
int ret = -1;
|
||||
bool v;
|
||||
int i;
|
||||
acl_t acl;
|
||||
acl_entry_t entry;
|
||||
acl_tag_t tag_type;
|
||||
void *qualifier_p;
|
||||
acl_permset_t permset;
|
||||
|
||||
acl = acl_get_file(path_p, ACL_TYPE_ACCESS);
|
||||
if (acl == NULL)
|
||||
goto out;
|
||||
|
||||
// prune entries by uid
|
||||
for (i = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry); i == 1; i = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry)) {
|
||||
if (acl_get_tag_type(entry, &tag_type) != 0)
|
||||
return -1;
|
||||
if (tag_type != ACL_USER)
|
||||
continue;
|
||||
|
||||
qualifier_p = acl_get_qualifier(entry);
|
||||
if (qualifier_p == NULL)
|
||||
return -1;
|
||||
v = *(uid_t *)qualifier_p == uid;
|
||||
acl_free(qualifier_p);
|
||||
|
||||
if (!v)
|
||||
continue;
|
||||
|
||||
acl_delete_entry(acl, entry);
|
||||
}
|
||||
|
||||
if (plen == 0)
|
||||
goto set;
|
||||
|
||||
if (acl_create_entry(&acl, &entry) != 0)
|
||||
goto out;
|
||||
if (acl_get_permset(entry, &permset) != 0)
|
||||
goto out;
|
||||
for (i = 0; i < plen; i++) {
|
||||
if (acl_add_perm(permset, perms[i]) != 0)
|
||||
goto out;
|
||||
}
|
||||
if (acl_set_tag_type(entry, ACL_USER) != 0)
|
||||
goto out;
|
||||
if (acl_set_qualifier(entry, (void *)&uid) != 0)
|
||||
goto out;
|
||||
|
||||
set:
|
||||
if (acl_calc_mask(&acl) != 0)
|
||||
goto out;
|
||||
if (acl_valid(acl) != 0)
|
||||
goto out;
|
||||
if (acl_set_file(path_p, ACL_TYPE_ACCESS, acl) == 0)
|
||||
ret = 0;
|
||||
|
||||
out:
|
||||
free((void *)path_p);
|
||||
if (acl != NULL)
|
||||
acl_free((void *)acl);
|
||||
return ret;
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
#include <sys/acl.h>
|
||||
|
||||
int f_acl_update_file_by_uid(const char *path_p, uid_t uid, acl_perm_t *perms, size_t plen);
|
||||
@@ -1,90 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/system"
|
||||
)
|
||||
|
||||
type bundleInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
|
||||
// passed through to [fst.Config]
|
||||
ID string `json:"id"`
|
||||
// passed through to [fst.Config]
|
||||
AppID int `json:"app_id"`
|
||||
// passed through to [fst.Config]
|
||||
Groups []string `json:"groups,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
UserNS bool `json:"userns,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
Net bool `json:"net,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
Dev bool `json:"dev,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
NoNewSession bool `json:"no_new_session,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
MapRealUID bool `json:"map_real_uid,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
DirectWayland bool `json:"direct_wayland,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
SystemBus *dbus.Config `json:"system_bus,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
SessionBus *dbus.Config `json:"session_bus,omitempty"`
|
||||
// passed through to [fst.Config]
|
||||
Enablements system.Enablements `json:"enablements"`
|
||||
|
||||
// passed through inverted to [bwrap.SyscallPolicy]
|
||||
Devel bool `json:"devel,omitempty"`
|
||||
// passed through to [bwrap.SyscallPolicy]
|
||||
Multiarch bool `json:"multiarch,omitempty"`
|
||||
// passed through to [bwrap.SyscallPolicy]
|
||||
Bluetooth bool `json:"bluetooth,omitempty"`
|
||||
|
||||
// allow gpu access within sandbox
|
||||
GPU bool `json:"gpu"`
|
||||
// store path to nixGL mesa wrappers
|
||||
Mesa string `json:"mesa,omitempty"`
|
||||
// store path to nixGL source
|
||||
NixGL string `json:"nix_gl,omitempty"`
|
||||
// store path to activate-and-exec script
|
||||
Launcher string `json:"launcher"`
|
||||
// store path to /run/current-system
|
||||
CurrentSystem string `json:"current_system"`
|
||||
// store path to home-manager activation package
|
||||
ActivationPackage string `json:"activation_package"`
|
||||
}
|
||||
|
||||
func loadBundleInfo(name string, beforeFail func()) *bundleInfo {
|
||||
bundle := new(bundleInfo)
|
||||
if f, err := os.Open(name); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot open bundle: %v", err)
|
||||
} else if err = json.NewDecoder(f).Decode(&bundle); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot parse bundle metadata: %v", err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
log.Printf("cannot close bundle metadata: %v", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
if bundle.ID == "" {
|
||||
beforeFail()
|
||||
log.Fatal("application identifier must not be empty")
|
||||
}
|
||||
|
||||
return bundle
|
||||
}
|
||||
|
||||
func formatHostname(name string) string {
|
||||
if h, err := os.Hostname(); err != nil {
|
||||
log.Printf("cannot get hostname: %v", err)
|
||||
return "fortify-" + name
|
||||
} else {
|
||||
return h + "-" + name
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func actionInstall(args []string) {
|
||||
set := flag.NewFlagSet("install", flag.ExitOnError)
|
||||
var (
|
||||
dropShellInstall bool
|
||||
dropShellActivate bool
|
||||
)
|
||||
set.BoolVar(&dropShellInstall, "si", false, "Drop to a shell on installation")
|
||||
set.BoolVar(&dropShellActivate, "sa", false, "Drop to a shell on activation")
|
||||
|
||||
// Ignore errors; set is set for ExitOnError.
|
||||
_ = set.Parse(args)
|
||||
|
||||
args = set.Args()
|
||||
|
||||
if len(args) != 1 {
|
||||
log.Fatal("invalid argument")
|
||||
}
|
||||
pkgPath := args[0]
|
||||
if !path.IsAbs(pkgPath) {
|
||||
if dir, err := os.Getwd(); err != nil {
|
||||
log.Fatalf("cannot get current directory: %v", err)
|
||||
} else {
|
||||
pkgPath = path.Join(dir, pkgPath)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Look up paths to programs started by fpkg.
|
||||
This is done here to ease error handling as cleanup is not yet required.
|
||||
*/
|
||||
|
||||
var (
|
||||
_ = lookPath("zstd")
|
||||
tar = lookPath("tar")
|
||||
chmod = lookPath("chmod")
|
||||
rm = lookPath("rm")
|
||||
)
|
||||
|
||||
/*
|
||||
Extract package and set up for cleanup.
|
||||
*/
|
||||
|
||||
var workDir string
|
||||
if p, err := os.MkdirTemp("", "fpkg.*"); err != nil {
|
||||
log.Fatalf("cannot create temporary directory: %v", err)
|
||||
} else {
|
||||
workDir = p
|
||||
}
|
||||
cleanup := func() {
|
||||
// should be faster than a native implementation
|
||||
mustRun(chmod, "-R", "+w", workDir)
|
||||
mustRun(rm, "-rf", workDir)
|
||||
}
|
||||
beforeRunFail.Store(&cleanup)
|
||||
|
||||
mustRun(tar, "-C", workDir, "-xf", pkgPath)
|
||||
|
||||
/*
|
||||
Parse bundle and app metadata, do pre-install checks.
|
||||
*/
|
||||
|
||||
bundle := loadBundleInfo(path.Join(workDir, "bundle.json"), cleanup)
|
||||
pathSet := pathSetByApp(bundle.ID)
|
||||
|
||||
app := bundle
|
||||
if s, err := os.Stat(pathSet.metaPath); err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
cleanup()
|
||||
log.Fatalf("cannot access %q: %v", pathSet.metaPath, err)
|
||||
}
|
||||
// did not modify app, clean installation condition met later
|
||||
} else if s.IsDir() {
|
||||
cleanup()
|
||||
log.Fatalf("metadata path %q is not a file", pathSet.metaPath)
|
||||
} else {
|
||||
app = loadBundleInfo(pathSet.metaPath, cleanup)
|
||||
if app.ID != bundle.ID {
|
||||
cleanup()
|
||||
log.Fatalf("app %q claims to have identifier %q", bundle.ID, app.ID)
|
||||
}
|
||||
// sec: should verify credentials
|
||||
}
|
||||
|
||||
if app != bundle {
|
||||
// do not try to re-install
|
||||
if app.NixGL == bundle.NixGL &&
|
||||
app.CurrentSystem == bundle.CurrentSystem &&
|
||||
app.Launcher == bundle.Launcher &&
|
||||
app.ActivationPackage == bundle.ActivationPackage {
|
||||
cleanup()
|
||||
log.Printf("package %q is identical to local application %q", pkgPath, app.ID)
|
||||
internal.Exit(0)
|
||||
}
|
||||
|
||||
// AppID determines uid
|
||||
if app.AppID != bundle.AppID {
|
||||
cleanup()
|
||||
log.Fatalf("package %q app id %d differs from installed %d", pkgPath, bundle.AppID, app.AppID)
|
||||
}
|
||||
|
||||
// sec: should compare version string
|
||||
fmsg.Verbosef("installing application %q version %q over local %q", bundle.ID, bundle.Version, app.Version)
|
||||
} else {
|
||||
fmsg.Verbosef("application %q clean installation", bundle.ID)
|
||||
// sec: should install credentials
|
||||
}
|
||||
|
||||
/*
|
||||
Setup steps for files owned by the target user.
|
||||
*/
|
||||
|
||||
withCacheDir("install", []string{
|
||||
// export inner bundle path in the environment
|
||||
"export BUNDLE=" + fst.Tmp + "/bundle",
|
||||
// replace inner /etc
|
||||
"mkdir -p etc",
|
||||
"chmod -R +w etc",
|
||||
"rm -rf etc",
|
||||
"cp -dRf $BUNDLE/etc etc",
|
||||
// replace inner /nix
|
||||
"mkdir -p nix",
|
||||
"chmod -R +w nix",
|
||||
"rm -rf nix",
|
||||
"cp -dRf /nix nix",
|
||||
// copy from binary cache
|
||||
"nix copy --offline --no-check-sigs --all --from file://$BUNDLE/res --to $PWD",
|
||||
// deduplicate nix store
|
||||
"nix store --offline --store $PWD optimise",
|
||||
// make cache directory world-readable for autoetc
|
||||
"chmod 0755 .",
|
||||
}, workDir, bundle, pathSet, dropShellInstall, cleanup)
|
||||
|
||||
if bundle.GPU {
|
||||
withCacheDir("mesa-wrappers", []string{
|
||||
// link nixGL mesa wrappers
|
||||
"mkdir -p nix/.nixGL",
|
||||
"ln -s " + bundle.Mesa + "/bin/nixGLIntel nix/.nixGL/nixGL",
|
||||
"ln -s " + bundle.Mesa + "/bin/nixVulkanIntel nix/.nixGL/nixVulkan",
|
||||
}, workDir, bundle, pathSet, false, cleanup)
|
||||
}
|
||||
|
||||
/*
|
||||
Activate home-manager generation.
|
||||
*/
|
||||
|
||||
withNixDaemon("activate", []string{
|
||||
// clean up broken links
|
||||
"mkdir -p .local/state/{nix,home-manager}",
|
||||
"chmod -R +w .local/state/{nix,home-manager}",
|
||||
"rm -rf .local/state/{nix,home-manager}",
|
||||
// run activation script
|
||||
bundle.ActivationPackage + "/activate",
|
||||
}, false, func(config *fst.Config) *fst.Config { return config }, bundle, pathSet, dropShellActivate, cleanup)
|
||||
|
||||
/*
|
||||
Installation complete. Write metadata to block re-installs or downgrades.
|
||||
*/
|
||||
|
||||
// serialise metadata to ensure consistency
|
||||
if f, err := os.OpenFile(pathSet.metaPath+"~", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644); err != nil {
|
||||
cleanup()
|
||||
log.Fatalf("cannot create metadata file: %v", err)
|
||||
} else if err = json.NewEncoder(f).Encode(bundle); err != nil {
|
||||
cleanup()
|
||||
log.Fatalf("cannot write metadata: %v", err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
log.Printf("cannot close metadata file: %v", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
if err := os.Rename(pathSet.metaPath+"~", pathSet.metaPath); err != nil {
|
||||
cleanup()
|
||||
log.Fatalf("cannot rename metadata file: %v", err)
|
||||
}
|
||||
|
||||
cleanup()
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const shell = "/run/current-system/sw/bin/bash"
|
||||
|
||||
func init() {
|
||||
if err := os.Setenv("SHELL", shell); err != nil {
|
||||
log.Fatalf("cannot set $SHELL: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
flagVerbose bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&flagVerbose, "v", false, "Verbose output")
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmsg.Prepare("fpkg")
|
||||
|
||||
flag.Parse()
|
||||
fmsg.Store(flagVerbose)
|
||||
|
||||
args := flag.Args()
|
||||
if len(args) < 1 {
|
||||
log.Fatal("invalid argument")
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
case "install":
|
||||
actionInstall(args[1:])
|
||||
case "start":
|
||||
actionStart(args[1:])
|
||||
|
||||
default:
|
||||
log.Fatal("invalid argument")
|
||||
}
|
||||
|
||||
internal.Exit(0)
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
var (
|
||||
dataHome string
|
||||
)
|
||||
|
||||
func init() {
|
||||
// dataHome
|
||||
if p, ok := os.LookupEnv("FORTIFY_DATA_HOME"); ok {
|
||||
dataHome = p
|
||||
} else {
|
||||
dataHome = "/var/lib/fortify/" + strconv.Itoa(os.Getuid())
|
||||
}
|
||||
}
|
||||
|
||||
func lookPath(file string) string {
|
||||
if p, err := exec.LookPath(file); err != nil {
|
||||
log.Fatalf("%s: command not found", file)
|
||||
return ""
|
||||
} else {
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
var beforeRunFail = new(atomic.Pointer[func()])
|
||||
|
||||
func mustRun(name string, arg ...string) {
|
||||
fmsg.Verbosef("spawning process: %q %q", name, arg)
|
||||
cmd := exec.Command(name, arg...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
if f := beforeRunFail.Swap(nil); f != nil {
|
||||
(*f)()
|
||||
}
|
||||
log.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
type appPathSet struct {
|
||||
// ${dataHome}/${id}
|
||||
baseDir string
|
||||
// ${baseDir}/app
|
||||
metaPath string
|
||||
// ${baseDir}/files
|
||||
homeDir string
|
||||
// ${baseDir}/cache
|
||||
cacheDir string
|
||||
// ${baseDir}/cache/nix
|
||||
nixPath string
|
||||
}
|
||||
|
||||
func pathSetByApp(id string) *appPathSet {
|
||||
pathSet := new(appPathSet)
|
||||
pathSet.baseDir = path.Join(dataHome, id)
|
||||
pathSet.metaPath = path.Join(pathSet.baseDir, "app")
|
||||
pathSet.homeDir = path.Join(pathSet.baseDir, "files")
|
||||
pathSet.cacheDir = path.Join(pathSet.baseDir, "cache")
|
||||
pathSet.nixPath = path.Join(pathSet.cacheDir, "nix")
|
||||
return pathSet
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
)
|
||||
|
||||
func actionStart(args []string) {
|
||||
set := flag.NewFlagSet("start", flag.ExitOnError)
|
||||
var (
|
||||
dropShell bool
|
||||
dropShellNixGL bool
|
||||
autoDrivers bool
|
||||
)
|
||||
set.BoolVar(&dropShell, "s", false, "Drop to a shell")
|
||||
set.BoolVar(&dropShellNixGL, "sg", false, "Drop to a shell on nixGL build")
|
||||
set.BoolVar(&autoDrivers, "autodrivers", false, "Attempt automatic opengl driver detection")
|
||||
|
||||
// Ignore errors; set is set for ExitOnError.
|
||||
_ = set.Parse(args)
|
||||
|
||||
args = set.Args()
|
||||
|
||||
if len(args) < 1 {
|
||||
log.Fatal("invalid argument")
|
||||
}
|
||||
|
||||
/*
|
||||
Parse app metadata.
|
||||
*/
|
||||
|
||||
id := args[0]
|
||||
pathSet := pathSetByApp(id)
|
||||
app := loadBundleInfo(pathSet.metaPath, func() {})
|
||||
if app.ID != id {
|
||||
log.Fatalf("app %q claims to have identifier %q", id, app.ID)
|
||||
}
|
||||
|
||||
/*
|
||||
Prepare nixGL.
|
||||
*/
|
||||
|
||||
if app.GPU && autoDrivers {
|
||||
withNixDaemon("nix-gl", []string{
|
||||
"mkdir -p /nix/.nixGL/auto",
|
||||
"rm -rf /nix/.nixGL/auto",
|
||||
"export NIXPKGS_ALLOW_UNFREE=1",
|
||||
"nix build --impure " +
|
||||
"--out-link /nix/.nixGL/auto/opengl " +
|
||||
"--override-input nixpkgs path:/etc/nixpkgs " +
|
||||
"path:" + app.NixGL,
|
||||
"nix build --impure " +
|
||||
"--out-link /nix/.nixGL/auto/vulkan " +
|
||||
"--override-input nixpkgs path:/etc/nixpkgs " +
|
||||
"path:" + app.NixGL + "#nixVulkanNvidia",
|
||||
}, true, func(config *fst.Config) *fst.Config {
|
||||
config.Confinement.Sandbox.Filesystem = append(config.Confinement.Sandbox.Filesystem, []*fst.FilesystemConfig{
|
||||
{Src: "/etc/resolv.conf"},
|
||||
{Src: "/sys/block"},
|
||||
{Src: "/sys/bus"},
|
||||
{Src: "/sys/class"},
|
||||
{Src: "/sys/dev"},
|
||||
{Src: "/sys/devices"},
|
||||
}...)
|
||||
appendGPUFilesystem(config)
|
||||
return config
|
||||
}, app, pathSet, dropShellNixGL, func() {})
|
||||
}
|
||||
|
||||
/*
|
||||
Create app configuration.
|
||||
*/
|
||||
|
||||
command := make([]string, 1, len(args))
|
||||
if !dropShell {
|
||||
command[0] = app.Launcher
|
||||
} else {
|
||||
command[0] = shell
|
||||
}
|
||||
command = append(command, args[1:]...)
|
||||
|
||||
config := &fst.Config{
|
||||
ID: app.ID,
|
||||
Command: command,
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: app.AppID,
|
||||
Groups: app.Groups,
|
||||
Username: "fortify",
|
||||
Inner: path.Join("/data/data", app.ID),
|
||||
Outer: pathSet.homeDir,
|
||||
Sandbox: &fst.SandboxConfig{
|
||||
Hostname: formatHostname(app.Name),
|
||||
UserNS: app.UserNS,
|
||||
Net: app.Net,
|
||||
Dev: app.Dev,
|
||||
Syscall: &bwrap.SyscallPolicy{DenyDevel: !app.Devel, Multiarch: app.Multiarch, Bluetooth: app.Bluetooth},
|
||||
NoNewSession: app.NoNewSession || dropShell,
|
||||
MapRealUID: app.MapRealUID,
|
||||
DirectWayland: app.DirectWayland,
|
||||
Filesystem: []*fst.FilesystemConfig{
|
||||
{Src: path.Join(pathSet.nixPath, "store"), Dst: "/nix/store", Must: true},
|
||||
{Src: pathSet.metaPath, Dst: path.Join(fst.Tmp, "app"), Must: true},
|
||||
{Src: "/etc/resolv.conf"},
|
||||
{Src: "/sys/block"},
|
||||
{Src: "/sys/bus"},
|
||||
{Src: "/sys/class"},
|
||||
{Src: "/sys/dev"},
|
||||
{Src: "/sys/devices"},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(pathSet.cacheDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
ExtraPerms: []*fst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
},
|
||||
SystemBus: app.SystemBus,
|
||||
SessionBus: app.SessionBus,
|
||||
Enablements: app.Enablements,
|
||||
},
|
||||
}
|
||||
|
||||
/*
|
||||
Expose GPU devices.
|
||||
*/
|
||||
|
||||
if app.GPU {
|
||||
config.Confinement.Sandbox.Filesystem = append(config.Confinement.Sandbox.Filesystem,
|
||||
&fst.FilesystemConfig{Src: path.Join(pathSet.nixPath, ".nixGL"), Dst: path.Join(fst.Tmp, "nixGL")})
|
||||
appendGPUFilesystem(config)
|
||||
}
|
||||
|
||||
/*
|
||||
Spawn app.
|
||||
*/
|
||||
|
||||
fortifyApp(config, func() {})
|
||||
internal.Exit(0)
|
||||
}
|
||||
|
||||
func appendGPUFilesystem(config *fst.Config) {
|
||||
config.Confinement.Sandbox.Filesystem = append(config.Confinement.Sandbox.Filesystem, []*fst.FilesystemConfig{
|
||||
// flatpak commit 763a686d874dd668f0236f911de00b80766ffe79
|
||||
{Src: "/dev/dri", Device: true},
|
||||
// mali
|
||||
{Src: "/dev/mali", Device: true},
|
||||
{Src: "/dev/mali0", Device: true},
|
||||
{Src: "/dev/umplock", Device: true},
|
||||
// nvidia
|
||||
{Src: "/dev/nvidiactl", Device: true},
|
||||
{Src: "/dev/nvidia-modeset", Device: true},
|
||||
// nvidia OpenCL/CUDA
|
||||
{Src: "/dev/nvidia-uvm", Device: true},
|
||||
{Src: "/dev/nvidia-uvm-tools", Device: true},
|
||||
|
||||
// flatpak commit d2dff2875bb3b7e2cd92d8204088d743fd07f3ff
|
||||
{Src: "/dev/nvidia0", Device: true}, {Src: "/dev/nvidia1", Device: true},
|
||||
{Src: "/dev/nvidia2", Device: true}, {Src: "/dev/nvidia3", Device: true},
|
||||
{Src: "/dev/nvidia4", Device: true}, {Src: "/dev/nvidia5", Device: true},
|
||||
{Src: "/dev/nvidia6", Device: true}, {Src: "/dev/nvidia7", Device: true},
|
||||
{Src: "/dev/nvidia8", Device: true}, {Src: "/dev/nvidia9", Device: true},
|
||||
{Src: "/dev/nvidia10", Device: true}, {Src: "/dev/nvidia11", Device: true},
|
||||
{Src: "/dev/nvidia12", Device: true}, {Src: "/dev/nvidia13", Device: true},
|
||||
{Src: "/dev/nvidia14", Device: true}, {Src: "/dev/nvidia15", Device: true},
|
||||
{Src: "/dev/nvidia16", Device: true}, {Src: "/dev/nvidia17", Device: true},
|
||||
{Src: "/dev/nvidia18", Device: true}, {Src: "/dev/nvidia19", Device: true},
|
||||
}...)
|
||||
}
|
||||
101
cmd/fpkg/with.go
101
cmd/fpkg/with.go
@@ -1,101 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
)
|
||||
|
||||
func withNixDaemon(
|
||||
action string, command []string, net bool, updateConfig func(config *fst.Config) *fst.Config,
|
||||
app *bundleInfo, pathSet *appPathSet, dropShell bool, beforeFail func(),
|
||||
) {
|
||||
fortifyAppDropShell(updateConfig(&fst.Config{
|
||||
ID: app.ID,
|
||||
Command: []string{shell, "-lc", "rm -f /nix/var/nix/daemon-socket/socket && " +
|
||||
// start nix-daemon
|
||||
"nix-daemon --store / & " +
|
||||
// wait for socket to appear
|
||||
"(while [ ! -S /nix/var/nix/daemon-socket/socket ]; do sleep 0.01; done) && " +
|
||||
// create directory so nix stops complaining
|
||||
"mkdir -p /nix/var/nix/profiles/per-user/root/channels && " +
|
||||
strings.Join(command, " && ") +
|
||||
// terminate nix-daemon
|
||||
" && pkill nix-daemon",
|
||||
},
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: app.AppID,
|
||||
Username: "fortify",
|
||||
Inner: path.Join("/data/data", app.ID),
|
||||
Outer: pathSet.homeDir,
|
||||
Sandbox: &fst.SandboxConfig{
|
||||
Hostname: formatHostname(app.Name) + "-" + action,
|
||||
UserNS: true, // nix sandbox requires userns
|
||||
Net: net,
|
||||
Syscall: &bwrap.SyscallPolicy{Multiarch: true},
|
||||
NoNewSession: dropShell,
|
||||
Filesystem: []*fst.FilesystemConfig{
|
||||
{Src: pathSet.nixPath, Dst: "/nix", Write: true, Must: true},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(pathSet.cacheDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
ExtraPerms: []*fst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
},
|
||||
},
|
||||
}), dropShell, beforeFail)
|
||||
}
|
||||
|
||||
func withCacheDir(action string, command []string, workDir string, app *bundleInfo, pathSet *appPathSet, dropShell bool, beforeFail func()) {
|
||||
fortifyAppDropShell(&fst.Config{
|
||||
ID: app.ID,
|
||||
Command: []string{shell, "-lc", strings.Join(command, " && ")},
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: app.AppID,
|
||||
Username: "nixos",
|
||||
Inner: path.Join("/data/data", app.ID, "cache"),
|
||||
Outer: pathSet.cacheDir, // this also ensures cacheDir via shim
|
||||
Sandbox: &fst.SandboxConfig{
|
||||
Hostname: formatHostname(app.Name) + "-" + action,
|
||||
Syscall: &bwrap.SyscallPolicy{Multiarch: true},
|
||||
NoNewSession: dropShell,
|
||||
Filesystem: []*fst.FilesystemConfig{
|
||||
{Src: path.Join(workDir, "nix"), Dst: "/nix", Must: true},
|
||||
{Src: workDir, Dst: path.Join(fst.Tmp, "bundle"), Must: true},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(workDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
ExtraPerms: []*fst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
{Path: workDir, Execute: true},
|
||||
},
|
||||
},
|
||||
}, dropShell, beforeFail)
|
||||
}
|
||||
|
||||
func fortifyAppDropShell(config *fst.Config, dropShell bool, beforeFail func()) {
|
||||
if dropShell {
|
||||
config.Command = []string{shell, "-l"}
|
||||
fortifyApp(config, beforeFail)
|
||||
beforeFail()
|
||||
internal.Exit(0)
|
||||
}
|
||||
fortifyApp(config, beforeFail)
|
||||
}
|
||||
257
cmd/hakurei/command.go
Normal file
257
cmd/hakurei/command.go
Normal file
@@ -0,0 +1,257 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"hakurei.app/command"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/app"
|
||||
"hakurei.app/internal/app/state"
|
||||
"hakurei.app/internal/hlog"
|
||||
"hakurei.app/system"
|
||||
"hakurei.app/system/dbus"
|
||||
)
|
||||
|
||||
func buildCommand(out io.Writer) command.Command {
|
||||
var (
|
||||
flagVerbose bool
|
||||
flagJSON bool
|
||||
)
|
||||
c := command.New(out, log.Printf, "hakurei", func([]string) error { internal.InstallOutput(flagVerbose); return nil }).
|
||||
Flag(&flagVerbose, "v", command.BoolFlag(false), "Increase log verbosity").
|
||||
Flag(&flagJSON, "json", command.BoolFlag(false), "Serialise output in JSON when applicable")
|
||||
|
||||
c.Command("shim", command.UsageInternal, func([]string) error { app.ShimMain(); return errSuccess })
|
||||
|
||||
c.Command("app", "Load app from configuration file", func(args []string) error {
|
||||
if len(args) < 1 {
|
||||
log.Fatal("app requires at least 1 argument")
|
||||
}
|
||||
|
||||
// config extraArgs...
|
||||
config := tryPath(args[0])
|
||||
config.Args = append(config.Args, args[1:]...)
|
||||
|
||||
runApp(config)
|
||||
panic("unreachable")
|
||||
})
|
||||
|
||||
{
|
||||
var (
|
||||
dbusConfigSession string
|
||||
dbusConfigSystem string
|
||||
mpris bool
|
||||
dbusVerbose bool
|
||||
|
||||
fid string
|
||||
aid int
|
||||
groups command.RepeatableFlag
|
||||
homeDir string
|
||||
userName string
|
||||
|
||||
wayland, x11, dBus, pulse bool
|
||||
)
|
||||
|
||||
c.NewCommand("run", "Configure and start a permissive default sandbox", func(args []string) error {
|
||||
// initialise config from flags
|
||||
config := &hst.Config{
|
||||
ID: fid,
|
||||
Args: args,
|
||||
}
|
||||
|
||||
if aid < 0 || aid > 9999 {
|
||||
log.Fatalf("aid %d out of range", aid)
|
||||
}
|
||||
|
||||
// resolve home/username from os when flag is unset
|
||||
var (
|
||||
passwd *user.User
|
||||
passwdOnce sync.Once
|
||||
passwdFunc = func() {
|
||||
var us string
|
||||
if uid, err := std.Uid(aid); err != nil {
|
||||
hlog.PrintBaseError(err, "cannot obtain uid from setuid wrapper:")
|
||||
os.Exit(1)
|
||||
} else {
|
||||
us = strconv.Itoa(uid)
|
||||
}
|
||||
|
||||
if u, err := user.LookupId(us); err != nil {
|
||||
hlog.Verbosef("cannot look up uid %s", us)
|
||||
passwd = &user.User{
|
||||
Uid: us,
|
||||
Gid: us,
|
||||
Username: "chronos",
|
||||
Name: "Hakurei Permissive Default",
|
||||
HomeDir: "/var/empty",
|
||||
}
|
||||
} else {
|
||||
passwd = u
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if homeDir == "os" {
|
||||
passwdOnce.Do(passwdFunc)
|
||||
homeDir = passwd.HomeDir
|
||||
}
|
||||
|
||||
if userName == "chronos" {
|
||||
passwdOnce.Do(passwdFunc)
|
||||
userName = passwd.Username
|
||||
}
|
||||
|
||||
config.Identity = aid
|
||||
config.Groups = groups
|
||||
config.Data = homeDir
|
||||
config.Username = userName
|
||||
|
||||
if wayland {
|
||||
config.Enablements |= system.EWayland
|
||||
}
|
||||
if x11 {
|
||||
config.Enablements |= system.EX11
|
||||
}
|
||||
if dBus {
|
||||
config.Enablements |= system.EDBus
|
||||
}
|
||||
if pulse {
|
||||
config.Enablements |= system.EPulse
|
||||
}
|
||||
|
||||
// parse D-Bus config file from flags if applicable
|
||||
if dBus {
|
||||
if dbusConfigSession == "builtin" {
|
||||
config.SessionBus = dbus.NewConfig(fid, true, mpris)
|
||||
} else {
|
||||
if conf, err := dbus.NewConfigFromFile(dbusConfigSession); err != nil {
|
||||
log.Fatalf("cannot load session bus proxy config from %q: %s", dbusConfigSession, err)
|
||||
} else {
|
||||
config.SessionBus = conf
|
||||
}
|
||||
}
|
||||
|
||||
// system bus proxy is optional
|
||||
if dbusConfigSystem != "nil" {
|
||||
if conf, err := dbus.NewConfigFromFile(dbusConfigSystem); err != nil {
|
||||
log.Fatalf("cannot load system bus proxy config from %q: %s", dbusConfigSystem, err)
|
||||
} else {
|
||||
config.SystemBus = conf
|
||||
}
|
||||
}
|
||||
|
||||
// override log from configuration
|
||||
if dbusVerbose {
|
||||
config.SessionBus.Log = true
|
||||
config.SystemBus.Log = true
|
||||
}
|
||||
}
|
||||
|
||||
// invoke app
|
||||
runApp(config)
|
||||
panic("unreachable")
|
||||
}).
|
||||
Flag(&dbusConfigSession, "dbus-config", command.StringFlag("builtin"),
|
||||
"Path to session bus proxy config file, or \"builtin\" for defaults").
|
||||
Flag(&dbusConfigSystem, "dbus-system", command.StringFlag("nil"),
|
||||
"Path to system bus proxy config file, or \"nil\" to disable").
|
||||
Flag(&mpris, "mpris", command.BoolFlag(false),
|
||||
"Allow owning MPRIS D-Bus path, has no effect if custom config is available").
|
||||
Flag(&dbusVerbose, "dbus-log", command.BoolFlag(false),
|
||||
"Force buffered logging in the D-Bus proxy").
|
||||
Flag(&fid, "id", command.StringFlag(""),
|
||||
"Reverse-DNS style Application identifier, leave empty to inherit instance identifier").
|
||||
Flag(&aid, "a", command.IntFlag(0),
|
||||
"Application identity").
|
||||
Flag(nil, "g", &groups,
|
||||
"Groups inherited by all container processes").
|
||||
Flag(&homeDir, "d", command.StringFlag("os"),
|
||||
"Container home directory").
|
||||
Flag(&userName, "u", command.StringFlag("chronos"),
|
||||
"Passwd user name within sandbox").
|
||||
Flag(&wayland, "wayland", command.BoolFlag(false),
|
||||
"Enable connection to Wayland via security-context-v1").
|
||||
Flag(&x11, "X", command.BoolFlag(false),
|
||||
"Enable direct connection to X11").
|
||||
Flag(&dBus, "dbus", command.BoolFlag(false),
|
||||
"Enable proxied connection to D-Bus").
|
||||
Flag(&pulse, "pulse", command.BoolFlag(false),
|
||||
"Enable direct connection to PulseAudio")
|
||||
}
|
||||
|
||||
var showFlagShort bool
|
||||
c.NewCommand("show", "Show live or local app configuration", func(args []string) error {
|
||||
switch len(args) {
|
||||
case 0: // system
|
||||
printShowSystem(os.Stdout, showFlagShort, flagJSON)
|
||||
|
||||
case 1: // instance
|
||||
name := args[0]
|
||||
config, entry := tryShort(name)
|
||||
if config == nil {
|
||||
config = tryPath(name)
|
||||
}
|
||||
printShowInstance(os.Stdout, time.Now().UTC(), entry, config, showFlagShort, flagJSON)
|
||||
|
||||
default:
|
||||
log.Fatal("show requires 1 argument")
|
||||
}
|
||||
return errSuccess
|
||||
}).Flag(&showFlagShort, "short", command.BoolFlag(false), "Omit filesystem information")
|
||||
|
||||
var psFlagShort bool
|
||||
c.NewCommand("ps", "List active instances", func(args []string) error {
|
||||
printPs(os.Stdout, time.Now().UTC(), state.NewMulti(std.Paths().RunDirPath), psFlagShort, flagJSON)
|
||||
return errSuccess
|
||||
}).Flag(&psFlagShort, "short", command.BoolFlag(false), "Print instance id")
|
||||
|
||||
c.Command("version", "Display version information", func(args []string) error {
|
||||
fmt.Println(internal.Version())
|
||||
return errSuccess
|
||||
})
|
||||
|
||||
c.Command("license", "Show full license text", func(args []string) error {
|
||||
fmt.Println(license)
|
||||
return errSuccess
|
||||
})
|
||||
|
||||
c.Command("template", "Produce a config template", func(args []string) error {
|
||||
printJSON(os.Stdout, false, hst.Template())
|
||||
return errSuccess
|
||||
})
|
||||
|
||||
c.Command("help", "Show this help message", func([]string) error {
|
||||
c.PrintHelp()
|
||||
return errSuccess
|
||||
})
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func runApp(config *hst.Config) {
|
||||
ctx, stop := signal.NotifyContext(context.Background(),
|
||||
syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop() // unreachable
|
||||
a := app.MustNew(ctx, std)
|
||||
|
||||
rs := new(app.RunState)
|
||||
if sa, err := a.Seal(config); err != nil {
|
||||
hlog.PrintBaseError(err, "cannot seal app:")
|
||||
internal.Exit(1)
|
||||
} else {
|
||||
internal.Exit(app.PrintRunStateErr(rs, sa.Run(rs)))
|
||||
}
|
||||
|
||||
*(*int)(nil) = 0 // not reached
|
||||
}
|
||||
81
cmd/hakurei/command_test.go
Normal file
81
cmd/hakurei/command_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"flag"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/command"
|
||||
)
|
||||
|
||||
func TestHelp(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
args []string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"main", []string{}, `
|
||||
Usage: hakurei [-h | --help] [-v] [--json] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
app Load app from configuration file
|
||||
run Configure and start a permissive default sandbox
|
||||
show Show live or local app configuration
|
||||
ps List active instances
|
||||
version Display version information
|
||||
license Show full license text
|
||||
template Produce a config template
|
||||
help Show this help message
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
"run", []string{"run", "-h"}, `
|
||||
Usage: hakurei run [-h | --help] [--dbus-config <value>] [--dbus-system <value>] [--mpris] [--dbus-log] [--id <value>] [-a <int>] [-g <value>] [-d <value>] [-u <value>] [--wayland] [-X] [--dbus] [--pulse] COMMAND [OPTIONS]
|
||||
|
||||
Flags:
|
||||
-X Enable direct connection to X11
|
||||
-a int
|
||||
Application identity
|
||||
-d string
|
||||
Container home directory (default "os")
|
||||
-dbus
|
||||
Enable proxied connection to D-Bus
|
||||
-dbus-config string
|
||||
Path to session bus proxy config file, or "builtin" for defaults (default "builtin")
|
||||
-dbus-log
|
||||
Force buffered logging in the D-Bus proxy
|
||||
-dbus-system string
|
||||
Path to system bus proxy config file, or "nil" to disable (default "nil")
|
||||
-g value
|
||||
Groups inherited by all container processes
|
||||
-id string
|
||||
Reverse-DNS style Application identifier, leave empty to inherit instance identifier
|
||||
-mpris
|
||||
Allow owning MPRIS D-Bus path, has no effect if custom config is available
|
||||
-pulse
|
||||
Enable direct connection to PulseAudio
|
||||
-u string
|
||||
Passwd user name within sandbox (default "chronos")
|
||||
-wayland
|
||||
Enable connection to Wayland via security-context-v1
|
||||
|
||||
`,
|
||||
},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out := new(bytes.Buffer)
|
||||
c := buildCommand(out)
|
||||
if err := c.Parse(tc.args); !errors.Is(err, command.ErrHelp) && !errors.Is(err, flag.ErrHelp) {
|
||||
t.Errorf("Parse: error = %v; want %v",
|
||||
err, command.ErrHelp)
|
||||
}
|
||||
if got := out.String(); got != tc.want {
|
||||
t.Errorf("Parse: %s want %s", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
51
cmd/hakurei/main.go
Normal file
51
cmd/hakurei/main.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
// this works around go:embed '..' limitation
|
||||
//go:generate cp ../../LICENSE .
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/hlog"
|
||||
"hakurei.app/internal/sys"
|
||||
)
|
||||
|
||||
var (
|
||||
errSuccess = errors.New("success")
|
||||
|
||||
//go:embed LICENSE
|
||||
license string
|
||||
)
|
||||
|
||||
func init() { hlog.Prepare("hakurei") }
|
||||
|
||||
var std sys.State = new(sys.Std)
|
||||
|
||||
func main() {
|
||||
// early init path, skips root check and duplicate PR_SET_DUMPABLE
|
||||
container.TryArgv0(hlog.Output{}, hlog.Prepare, internal.InstallOutput)
|
||||
|
||||
if err := container.SetDumpable(container.SUID_DUMP_DISABLE); err != nil {
|
||||
log.Printf("cannot set SUID_DUMP_DISABLE: %s", err)
|
||||
// not fatal: this program runs as the privileged user
|
||||
}
|
||||
|
||||
if os.Geteuid() == 0 {
|
||||
log.Fatal("this program must not run as root")
|
||||
}
|
||||
|
||||
buildCommand(os.Stderr).MustParse(os.Args[1:], func(err error) {
|
||||
hlog.Verbosef("command returned %v", err)
|
||||
if errors.Is(err, errSuccess) {
|
||||
hlog.BeforeExit()
|
||||
os.Exit(0)
|
||||
}
|
||||
// this catches faulty command handlers that fail to return before this point
|
||||
})
|
||||
log.Fatal("unreachable")
|
||||
}
|
||||
@@ -10,19 +10,19 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/app/state"
|
||||
"hakurei.app/internal/hlog"
|
||||
)
|
||||
|
||||
func tryPath(name string) (config *fst.Config) {
|
||||
func tryPath(name string) (config *hst.Config) {
|
||||
var r io.Reader
|
||||
config = new(fst.Config)
|
||||
config = new(hst.Config)
|
||||
|
||||
if name != "-" {
|
||||
r = tryFd(name)
|
||||
if r == nil {
|
||||
fmsg.Verbose("load configuration from file")
|
||||
hlog.Verbose("load configuration from file")
|
||||
|
||||
if f, err := os.Open(name); err != nil {
|
||||
log.Fatalf("cannot access configuration file %q: %s", name, err)
|
||||
@@ -50,9 +50,12 @@ func tryPath(name string) (config *fst.Config) {
|
||||
|
||||
func tryFd(name string) io.ReadCloser {
|
||||
if v, err := strconv.Atoi(name); err != nil {
|
||||
fmsg.Verbosef("name cannot be interpreted as int64: %v", err)
|
||||
if !errors.Is(err, strconv.ErrSyntax) {
|
||||
hlog.Verbosef("name cannot be interpreted as int64: %v", err)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
hlog.Verbosef("trying config stream from %d", v)
|
||||
fd := uintptr(v)
|
||||
if _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETFD, 0); errno != 0 {
|
||||
if errors.Is(errno, syscall.EBADF) {
|
||||
@@ -64,7 +67,7 @@ func tryFd(name string) io.ReadCloser {
|
||||
}
|
||||
}
|
||||
|
||||
func tryShort(name string) (config *fst.Config, instance *state.State) {
|
||||
func tryShort(name string) (config *hst.Config, entry *state.State) {
|
||||
likePrefix := false
|
||||
if len(name) <= 32 {
|
||||
likePrefix = true
|
||||
@@ -82,7 +85,7 @@ func tryShort(name string) (config *fst.Config, instance *state.State) {
|
||||
|
||||
// try to match from state store
|
||||
if likePrefix && len(name) >= 8 {
|
||||
fmsg.Verbose("argument looks like prefix")
|
||||
hlog.Verbose("argument looks like prefix")
|
||||
|
||||
s := state.NewMulti(std.Paths().RunDirPath)
|
||||
if entries, err := state.Join(s); err != nil {
|
||||
@@ -93,12 +96,12 @@ func tryShort(name string) (config *fst.Config, instance *state.State) {
|
||||
v := id.String()
|
||||
if strings.HasPrefix(v, name) {
|
||||
// match, use config from this state entry
|
||||
instance = entries[id]
|
||||
config = instance.Config
|
||||
entry = entries[id]
|
||||
config = entry.Config
|
||||
break
|
||||
}
|
||||
|
||||
fmsg.Verbosef("instance %s skipped", v)
|
||||
hlog.Verbosef("instance %s skipped", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,21 +12,21 @@ import (
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"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/state"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/app/state"
|
||||
"hakurei.app/internal/hlog"
|
||||
"hakurei.app/system/dbus"
|
||||
)
|
||||
|
||||
func printShowSystem(output io.Writer, short bool) {
|
||||
func printShowSystem(output io.Writer, short, flagJSON bool) {
|
||||
t := newPrinter(output)
|
||||
defer t.MustFlush()
|
||||
|
||||
info := new(fst.Info)
|
||||
info := new(hst.Info)
|
||||
|
||||
// get fid by querying uid of aid 0
|
||||
if uid, err := std.Uid(0); err != nil {
|
||||
fmsg.PrintBaseError(err, "cannot obtain uid from fsu:")
|
||||
hlog.PrintBaseError(err, "cannot obtain uid from setuid wrapper:")
|
||||
os.Exit(1)
|
||||
} else {
|
||||
info.User = (uid / 10000) - 100
|
||||
@@ -42,8 +42,8 @@ func printShowSystem(output io.Writer, short bool) {
|
||||
|
||||
func printShowInstance(
|
||||
output io.Writer, now time.Time,
|
||||
instance *state.State, config *fst.Config,
|
||||
short bool) {
|
||||
instance *state.State, config *hst.Config,
|
||||
short, flagJSON bool) {
|
||||
if flagJSON {
|
||||
if instance != nil {
|
||||
printJSON(output, short, instance)
|
||||
@@ -56,7 +56,7 @@ func printShowInstance(
|
||||
t := newPrinter(output)
|
||||
defer t.MustFlush()
|
||||
|
||||
if config.Confinement.Sandbox == nil {
|
||||
if config.Container == nil {
|
||||
mustPrint(output, "Warning: this configuration uses permissive defaults!\n\n")
|
||||
}
|
||||
|
||||
@@ -69,19 +69,21 @@ func printShowInstance(
|
||||
|
||||
t.Printf("App\n")
|
||||
if config.ID != "" {
|
||||
t.Printf(" ID:\t%d (%s)\n", config.Confinement.AppID, config.ID)
|
||||
t.Printf(" Identity:\t%d (%s)\n", config.Identity, config.ID)
|
||||
} else {
|
||||
t.Printf(" ID:\t%d\n", config.Confinement.AppID)
|
||||
t.Printf(" Identity:\t%d\n", config.Identity)
|
||||
}
|
||||
t.Printf(" Enablements:\t%s\n", config.Confinement.Enablements.String())
|
||||
if len(config.Confinement.Groups) > 0 {
|
||||
t.Printf(" Groups:\t%q\n", config.Confinement.Groups)
|
||||
t.Printf(" Enablements:\t%s\n", config.Enablements.String())
|
||||
if len(config.Groups) > 0 {
|
||||
t.Printf(" Groups:\t%s\n", strings.Join(config.Groups, ", "))
|
||||
}
|
||||
t.Printf(" Directory:\t%s\n", config.Confinement.Outer)
|
||||
if config.Confinement.Sandbox != nil {
|
||||
sandbox := config.Confinement.Sandbox
|
||||
if sandbox.Hostname != "" {
|
||||
t.Printf(" Hostname:\t%q\n", sandbox.Hostname)
|
||||
if config.Data != "" {
|
||||
t.Printf(" Data:\t%s\n", config.Data)
|
||||
}
|
||||
if config.Container != nil {
|
||||
container := config.Container
|
||||
if container.Hostname != "" {
|
||||
t.Printf(" Hostname:\t%s\n", container.Hostname)
|
||||
}
|
||||
flags := make([]string, 0, 7)
|
||||
writeFlag := func(name string, value bool) {
|
||||
@@ -89,38 +91,40 @@ func printShowInstance(
|
||||
flags = append(flags, name)
|
||||
}
|
||||
}
|
||||
writeFlag("userns", sandbox.UserNS)
|
||||
writeFlag("net", sandbox.Net)
|
||||
writeFlag("dev", sandbox.Dev)
|
||||
writeFlag("tty", sandbox.NoNewSession)
|
||||
writeFlag("mapuid", sandbox.MapRealUID)
|
||||
writeFlag("directwl", sandbox.DirectWayland)
|
||||
writeFlag("autoetc", sandbox.AutoEtc)
|
||||
writeFlag("userns", container.Userns)
|
||||
writeFlag("devel", container.Devel)
|
||||
writeFlag("net", container.Net)
|
||||
writeFlag("device", container.Device)
|
||||
writeFlag("tty", container.Tty)
|
||||
writeFlag("mapuid", container.MapRealUID)
|
||||
writeFlag("directwl", config.DirectWayland)
|
||||
writeFlag("autoetc", container.AutoEtc)
|
||||
if len(flags) == 0 {
|
||||
flags = append(flags, "none")
|
||||
}
|
||||
t.Printf(" Flags:\t%s\n", strings.Join(flags, " "))
|
||||
|
||||
etc := sandbox.Etc
|
||||
etc := container.Etc
|
||||
if etc == "" {
|
||||
etc = "/etc"
|
||||
}
|
||||
t.Printf(" Etc:\t%s\n", etc)
|
||||
|
||||
if len(sandbox.Override) > 0 {
|
||||
t.Printf(" Overrides:\t%s\n", strings.Join(sandbox.Override, " "))
|
||||
if len(container.Cover) > 0 {
|
||||
t.Printf(" Cover:\t%s\n", strings.Join(container.Cover, " "))
|
||||
}
|
||||
|
||||
// Env map[string]string `json:"env"`
|
||||
// Link [][2]string `json:"symlink"`
|
||||
t.Printf(" Path:\t%s\n", config.Path)
|
||||
}
|
||||
if len(config.Args) > 0 {
|
||||
t.Printf(" Arguments:\t%s\n", strings.Join(config.Args, " "))
|
||||
}
|
||||
t.Printf(" Command:\t%s\n", strings.Join(config.Command, " "))
|
||||
t.Printf("\n")
|
||||
|
||||
if !short {
|
||||
if config.Confinement.Sandbox != nil && len(config.Confinement.Sandbox.Filesystem) > 0 {
|
||||
if config.Container != nil && len(config.Container.Filesystem) > 0 {
|
||||
t.Printf("Filesystem\n")
|
||||
for _, f := range config.Confinement.Sandbox.Filesystem {
|
||||
for _, f := range config.Container.Filesystem {
|
||||
if f == nil {
|
||||
continue
|
||||
}
|
||||
@@ -148,9 +152,9 @@ func printShowInstance(
|
||||
}
|
||||
t.Printf("\n")
|
||||
}
|
||||
if len(config.Confinement.ExtraPerms) > 0 {
|
||||
if len(config.ExtraPerms) > 0 {
|
||||
t.Printf("Extra ACL\n")
|
||||
for _, p := range config.Confinement.ExtraPerms {
|
||||
for _, p := range config.ExtraPerms {
|
||||
if p == nil {
|
||||
continue
|
||||
}
|
||||
@@ -178,19 +182,19 @@ func printShowInstance(
|
||||
t.Printf(" Broadcast:\t%q\n", c.Broadcast)
|
||||
}
|
||||
}
|
||||
if config.Confinement.SessionBus != nil {
|
||||
if config.SessionBus != nil {
|
||||
t.Printf("Session bus\n")
|
||||
printDBus(config.Confinement.SessionBus)
|
||||
printDBus(config.SessionBus)
|
||||
t.Printf("\n")
|
||||
}
|
||||
if config.Confinement.SystemBus != nil {
|
||||
if config.SystemBus != nil {
|
||||
t.Printf("System bus\n")
|
||||
printDBus(config.Confinement.SystemBus)
|
||||
printDBus(config.SystemBus)
|
||||
t.Printf("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func printPs(output io.Writer, now time.Time, s state.Store, short bool) {
|
||||
func printPs(output io.Writer, now time.Time, s state.Store, short, flagJSON bool) {
|
||||
var entries state.Entries
|
||||
if e, err := state.Join(s); err != nil {
|
||||
log.Fatalf("cannot join store: %v", err)
|
||||
@@ -247,22 +251,26 @@ func printPs(output io.Writer, now time.Time, s state.Store, short bool) {
|
||||
t := newPrinter(output)
|
||||
defer t.MustFlush()
|
||||
|
||||
t.Println("\tInstance\tPID\tApp\tUptime\tEnablements\tCommand")
|
||||
t.Println("\tInstance\tPID\tApplication\tUptime")
|
||||
for _, e := range exp {
|
||||
var (
|
||||
es = "(No confinement information)"
|
||||
cs = "(No command information)"
|
||||
as = "(No configuration information)"
|
||||
)
|
||||
if e.Config != nil {
|
||||
es = e.Config.Confinement.Enablements.String()
|
||||
cs = fmt.Sprintf("%q", e.Config.Command)
|
||||
as = strconv.Itoa(e.Config.Confinement.AppID)
|
||||
if len(e.s) != 1<<5 {
|
||||
// unreachable
|
||||
log.Printf("possible store corruption: invalid instance string %s", e.s)
|
||||
continue
|
||||
}
|
||||
t.Printf("\t%s\t%d\t%s\t%s\t%s\t%s\n",
|
||||
e.s[:8], e.PID, as, now.Sub(e.Time).Round(time.Second).String(), strings.TrimPrefix(es, ", "), cs)
|
||||
|
||||
as := "(No configuration information)"
|
||||
if e.Config != nil {
|
||||
as = strconv.Itoa(e.Config.Identity)
|
||||
id := e.Config.ID
|
||||
if id == "" {
|
||||
id = "app.hakurei." + e.s[:8]
|
||||
}
|
||||
as += " (" + id + ")"
|
||||
}
|
||||
t.Printf("\t%s\t%d\t%s\t%s\n",
|
||||
e.s[:8], e.PID, as, now.Sub(e.Time).Round(time.Second).String())
|
||||
}
|
||||
t.Println()
|
||||
}
|
||||
|
||||
type expandedStateEntry struct {
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/app/state"
|
||||
"hakurei.app/system/dbus"
|
||||
)
|
||||
|
||||
var (
|
||||
testID = fst.ID{
|
||||
testID = state.ID{
|
||||
0x8e, 0x2c, 0x76, 0xb0,
|
||||
0x66, 0xda, 0xbe, 0x57,
|
||||
0x4c, 0xf0, 0x73, 0xbd,
|
||||
@@ -20,7 +20,7 @@ var (
|
||||
testState = &state.State{
|
||||
ID: testID,
|
||||
PID: 0xDEADBEEF,
|
||||
Config: fst.Template(),
|
||||
Config: hst.Template(),
|
||||
Time: testAppTime,
|
||||
}
|
||||
testTime = time.Unix(3752, 1).UTC()
|
||||
@@ -31,32 +31,33 @@ func Test_printShowInstance(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
instance *state.State
|
||||
config *fst.Config
|
||||
config *hst.Config
|
||||
short, json bool
|
||||
want string
|
||||
}{
|
||||
{"config", nil, fst.Template(), false, false, `App
|
||||
ID: 9 (org.chromium.Chromium)
|
||||
Enablements: Wayland, D-Bus, PulseAudio
|
||||
Groups: ["video"]
|
||||
Directory: /var/lib/persist/home/org.chromium.Chromium
|
||||
Hostname: "localhost"
|
||||
Flags: userns net dev tty mapuid autoetc
|
||||
{"config", nil, hst.Template(), false, false, `App
|
||||
Identity: 9 (org.chromium.Chromium)
|
||||
Enablements: wayland, dbus, pulseaudio
|
||||
Groups: video, dialout, plugdev
|
||||
Data: /var/lib/hakurei/u0/org.chromium.Chromium
|
||||
Hostname: localhost
|
||||
Flags: userns devel net device tty mapuid autoetc
|
||||
Etc: /etc
|
||||
Overrides: /var/run/nscd
|
||||
Command: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
|
||||
Cover: /var/run/nscd
|
||||
Path: /run/current-system/sw/bin/chromium
|
||||
Arguments: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
|
||||
|
||||
Filesystem
|
||||
+/nix/store
|
||||
+/run/current-system
|
||||
+/run/opengl-driver
|
||||
+/var/db/nix-channels
|
||||
w*/var/lib/fortify/u0/org.chromium.Chromium:/data/data/org.chromium.Chromium
|
||||
w*/var/lib/hakurei/u0/org.chromium.Chromium:/data/data/org.chromium.Chromium
|
||||
d+/dev/dri
|
||||
|
||||
Extra ACL
|
||||
--x+:/var/lib/fortify/u0
|
||||
rwx:/var/lib/fortify/u0/org.chromium.Chromium
|
||||
--x+:/var/lib/hakurei/u0
|
||||
rwx:/var/lib/hakurei/u0/org.chromium.Chromium
|
||||
|
||||
Session bus
|
||||
Filter: true
|
||||
@@ -70,44 +71,38 @@ System bus
|
||||
Talk: ["org.bluez" "org.freedesktop.Avahi" "org.freedesktop.UPower"]
|
||||
|
||||
`},
|
||||
{"config pd", nil, new(fst.Config), false, false, `Warning: this configuration uses permissive defaults!
|
||||
{"config pd", nil, new(hst.Config), false, false, `Warning: this configuration uses permissive defaults!
|
||||
|
||||
App
|
||||
ID: 0
|
||||
Enablements: (No enablements)
|
||||
Directory:
|
||||
Command:
|
||||
Identity: 0
|
||||
Enablements: (no enablements)
|
||||
|
||||
`},
|
||||
{"config flag none", nil, &fst.Config{Confinement: fst.ConfinementConfig{Sandbox: new(fst.SandboxConfig)}}, false, false, `App
|
||||
ID: 0
|
||||
Enablements: (No enablements)
|
||||
Directory:
|
||||
{"config flag none", nil, &hst.Config{Container: new(hst.ContainerConfig)}, false, false, `App
|
||||
Identity: 0
|
||||
Enablements: (no enablements)
|
||||
Flags: none
|
||||
Etc: /etc
|
||||
Command:
|
||||
Path:
|
||||
|
||||
`},
|
||||
{"config nil entries", nil, &fst.Config{Confinement: fst.ConfinementConfig{Sandbox: &fst.SandboxConfig{Filesystem: make([]*fst.FilesystemConfig, 1)}, ExtraPerms: make([]*fst.ExtraPermConfig, 1)}}, false, false, `App
|
||||
ID: 0
|
||||
Enablements: (No enablements)
|
||||
Directory:
|
||||
{"config nil entries", nil, &hst.Config{Container: &hst.ContainerConfig{Filesystem: make([]*hst.FilesystemConfig, 1)}, ExtraPerms: make([]*hst.ExtraPermConfig, 1)}, false, false, `App
|
||||
Identity: 0
|
||||
Enablements: (no enablements)
|
||||
Flags: none
|
||||
Etc: /etc
|
||||
Command:
|
||||
Path:
|
||||
|
||||
Filesystem
|
||||
|
||||
Extra ACL
|
||||
|
||||
`},
|
||||
{"config pd dbus see", nil, &fst.Config{Confinement: fst.ConfinementConfig{SessionBus: &dbus.Config{See: []string{"org.example.test"}}}}, false, false, `Warning: this configuration uses permissive defaults!
|
||||
{"config pd dbus see", nil, &hst.Config{SessionBus: &dbus.Config{See: []string{"org.example.test"}}}, false, false, `Warning: this configuration uses permissive defaults!
|
||||
|
||||
App
|
||||
ID: 0
|
||||
Enablements: (No enablements)
|
||||
Directory:
|
||||
Command:
|
||||
Identity: 0
|
||||
Enablements: (no enablements)
|
||||
|
||||
Session bus
|
||||
Filter: false
|
||||
@@ -115,32 +110,33 @@ Session bus
|
||||
|
||||
`},
|
||||
|
||||
{"instance", testState, fst.Template(), false, false, `State
|
||||
{"instance", testState, hst.Template(), false, false, `State
|
||||
Instance: 8e2c76b066dabe574cf073bdb46eb5c1 (3735928559)
|
||||
Uptime: 1h2m32s
|
||||
|
||||
App
|
||||
ID: 9 (org.chromium.Chromium)
|
||||
Enablements: Wayland, D-Bus, PulseAudio
|
||||
Groups: ["video"]
|
||||
Directory: /var/lib/persist/home/org.chromium.Chromium
|
||||
Hostname: "localhost"
|
||||
Flags: userns net dev tty mapuid autoetc
|
||||
Identity: 9 (org.chromium.Chromium)
|
||||
Enablements: wayland, dbus, pulseaudio
|
||||
Groups: video, dialout, plugdev
|
||||
Data: /var/lib/hakurei/u0/org.chromium.Chromium
|
||||
Hostname: localhost
|
||||
Flags: userns devel net device tty mapuid autoetc
|
||||
Etc: /etc
|
||||
Overrides: /var/run/nscd
|
||||
Command: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
|
||||
Cover: /var/run/nscd
|
||||
Path: /run/current-system/sw/bin/chromium
|
||||
Arguments: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
|
||||
|
||||
Filesystem
|
||||
+/nix/store
|
||||
+/run/current-system
|
||||
+/run/opengl-driver
|
||||
+/var/db/nix-channels
|
||||
w*/var/lib/fortify/u0/org.chromium.Chromium:/data/data/org.chromium.Chromium
|
||||
w*/var/lib/hakurei/u0/org.chromium.Chromium:/data/data/org.chromium.Chromium
|
||||
d+/dev/dri
|
||||
|
||||
Extra ACL
|
||||
--x+:/var/lib/fortify/u0
|
||||
rwx:/var/lib/fortify/u0/org.chromium.Chromium
|
||||
--x+:/var/lib/hakurei/u0
|
||||
rwx:/var/lib/hakurei/u0/org.chromium.Chromium
|
||||
|
||||
Session bus
|
||||
Filter: true
|
||||
@@ -154,17 +150,15 @@ System bus
|
||||
Talk: ["org.bluez" "org.freedesktop.Avahi" "org.freedesktop.UPower"]
|
||||
|
||||
`},
|
||||
{"instance pd", testState, new(fst.Config), false, false, `Warning: this configuration uses permissive defaults!
|
||||
{"instance pd", testState, new(hst.Config), false, false, `Warning: this configuration uses permissive defaults!
|
||||
|
||||
State
|
||||
Instance: 8e2c76b066dabe574cf073bdb46eb5c1 (3735928559)
|
||||
Uptime: 1h2m32s
|
||||
|
||||
App
|
||||
ID: 0
|
||||
Enablements: (No enablements)
|
||||
Directory:
|
||||
Command:
|
||||
Identity: 0
|
||||
Enablements: (no enablements)
|
||||
|
||||
`},
|
||||
|
||||
@@ -192,230 +186,15 @@ App
|
||||
"pid": 3735928559,
|
||||
"config": {
|
||||
"id": "org.chromium.Chromium",
|
||||
"command": [
|
||||
"path": "/run/current-system/sw/bin/chromium",
|
||||
"args": [
|
||||
"chromium",
|
||||
"--ignore-gpu-blocklist",
|
||||
"--disable-smooth-scrolling",
|
||||
"--enable-features=UseOzonePlatform",
|
||||
"--ozone-platform=wayland"
|
||||
],
|
||||
"confinement": {
|
||||
"app_id": 9,
|
||||
"groups": [
|
||||
"video"
|
||||
],
|
||||
"username": "chronos",
|
||||
"home_inner": "/var/lib/fortify",
|
||||
"home": "/var/lib/persist/home/org.chromium.Chromium",
|
||||
"sandbox": {
|
||||
"hostname": "localhost",
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"dev": true,
|
||||
"syscall": {
|
||||
"compat": false,
|
||||
"deny_devel": true,
|
||||
"multiarch": true,
|
||||
"linux32": false,
|
||||
"can": false,
|
||||
"bluetooth": false
|
||||
},
|
||||
"no_new_session": true,
|
||||
"map_real_uid": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"filesystem": [
|
||||
{
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"override": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
},
|
||||
"extra_perms": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/fortify/u0",
|
||||
"x": true
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
}
|
||||
],
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
"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
|
||||
},
|
||||
"enablements": 13
|
||||
}
|
||||
},
|
||||
"time": "1970-01-01T00:00:00.000000009Z"
|
||||
}
|
||||
`},
|
||||
{"json config", nil, fst.Template(), false, true, `{
|
||||
"id": "org.chromium.Chromium",
|
||||
"command": [
|
||||
"chromium",
|
||||
"--ignore-gpu-blocklist",
|
||||
"--disable-smooth-scrolling",
|
||||
"--enable-features=UseOzonePlatform",
|
||||
"--ozone-platform=wayland"
|
||||
],
|
||||
"confinement": {
|
||||
"app_id": 9,
|
||||
"groups": [
|
||||
"video"
|
||||
],
|
||||
"username": "chronos",
|
||||
"home_inner": "/var/lib/fortify",
|
||||
"home": "/var/lib/persist/home/org.chromium.Chromium",
|
||||
"sandbox": {
|
||||
"hostname": "localhost",
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"dev": true,
|
||||
"syscall": {
|
||||
"compat": false,
|
||||
"deny_devel": true,
|
||||
"multiarch": true,
|
||||
"linux32": false,
|
||||
"can": false,
|
||||
"bluetooth": false
|
||||
},
|
||||
"no_new_session": true,
|
||||
"map_real_uid": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"filesystem": [
|
||||
{
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"override": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
},
|
||||
"extra_perms": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/fortify/u0",
|
||||
"x": true
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
}
|
||||
],
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"enablements": 13,
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
@@ -440,7 +219,222 @@ App
|
||||
},
|
||||
"filter": true
|
||||
},
|
||||
"enablements": 13
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"username": "chronos",
|
||||
"shell": "/run/current-system/sw/bin/zsh",
|
||||
"data": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"dir": "/data/data/org.chromium.Chromium",
|
||||
"extra_perms": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/hakurei/u0",
|
||||
"x": true
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
}
|
||||
],
|
||||
"identity": 9,
|
||||
"groups": [
|
||||
"video",
|
||||
"dialout",
|
||||
"plugdev"
|
||||
],
|
||||
"container": {
|
||||
"hostname": "localhost",
|
||||
"wait_delay": -1,
|
||||
"seccomp_flags": 1,
|
||||
"seccomp_presets": 1,
|
||||
"seccomp_compat": true,
|
||||
"devel": true,
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"tty": true,
|
||||
"multiarch": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"map_real_uid": true,
|
||||
"device": true,
|
||||
"filesystem": [
|
||||
{
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"cover": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
}
|
||||
},
|
||||
"time": "1970-01-01T00:00:00.000000009Z"
|
||||
}
|
||||
`},
|
||||
{"json config", nil, hst.Template(), false, true, `{
|
||||
"id": "org.chromium.Chromium",
|
||||
"path": "/run/current-system/sw/bin/chromium",
|
||||
"args": [
|
||||
"chromium",
|
||||
"--ignore-gpu-blocklist",
|
||||
"--disable-smooth-scrolling",
|
||||
"--enable-features=UseOzonePlatform",
|
||||
"--ozone-platform=wayland"
|
||||
],
|
||||
"enablements": 13,
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
"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
|
||||
},
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"username": "chronos",
|
||||
"shell": "/run/current-system/sw/bin/zsh",
|
||||
"data": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"dir": "/data/data/org.chromium.Chromium",
|
||||
"extra_perms": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/hakurei/u0",
|
||||
"x": true
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
}
|
||||
],
|
||||
"identity": 9,
|
||||
"groups": [
|
||||
"video",
|
||||
"dialout",
|
||||
"plugdev"
|
||||
],
|
||||
"container": {
|
||||
"hostname": "localhost",
|
||||
"wait_delay": -1,
|
||||
"seccomp_flags": 1,
|
||||
"seccomp_presets": 1,
|
||||
"seccomp_compat": true,
|
||||
"devel": true,
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"tty": true,
|
||||
"multiarch": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"map_real_uid": true,
|
||||
"device": true,
|
||||
"filesystem": [
|
||||
{
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"cover": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
}
|
||||
}
|
||||
`},
|
||||
@@ -448,14 +442,8 @@ App
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
{
|
||||
v := flagJSON
|
||||
t.Cleanup(func() { flagJSON = v })
|
||||
flagJSON = tc.json
|
||||
}
|
||||
|
||||
output := new(strings.Builder)
|
||||
printShowInstance(output, testTime, tc.instance, tc.config, tc.short)
|
||||
printShowInstance(output, testTime, tc.instance, tc.config, tc.short, tc.json)
|
||||
if got := output.String(); got != tc.want {
|
||||
t.Errorf("printShowInstance: got\n%s\nwant\n%s",
|
||||
got, tc.want)
|
||||
@@ -472,23 +460,19 @@ func Test_printPs(t *testing.T) {
|
||||
short, json bool
|
||||
want string
|
||||
}{
|
||||
{"no entries", make(state.Entries), false, false, ` Instance PID App Uptime Enablements Command
|
||||
|
||||
`},
|
||||
{"no entries short", make(state.Entries), true, false, ``},
|
||||
{"nil instance", state.Entries{testID: nil}, false, false, ` Instance PID App Uptime Enablements Command
|
||||
|
||||
`},
|
||||
{"state corruption", state.Entries{fst.ID{}: testState}, false, false, ` Instance PID App Uptime Enablements Command
|
||||
{"no entries", make(state.Entries), false, false, " Instance PID Application Uptime\n"},
|
||||
{"no entries short", make(state.Entries), true, false, ""},
|
||||
{"nil instance", state.Entries{testID: nil}, false, false, " Instance PID Application Uptime\n"},
|
||||
{"state corruption", state.Entries{state.ID{}: testState}, false, false, " Instance PID Application Uptime\n"},
|
||||
|
||||
{"valid pd", state.Entries{testID: &state.State{ID: testID, PID: 1 << 8, Config: new(hst.Config), Time: testAppTime}}, false, false, ` Instance PID Application Uptime
|
||||
8e2c76b0 256 0 (app.hakurei.8e2c76b0) 1h2m32s
|
||||
`},
|
||||
|
||||
{"valid", state.Entries{testID: testState}, false, false, ` Instance PID App Uptime Enablements Command
|
||||
8e2c76b0 3735928559 9 1h2m32s Wayland, D-Bus, PulseAudio ["chromium" "--ignore-gpu-blocklist" "--disable-smooth-scrolling" "--enable-features=UseOzonePlatform" "--ozone-platform=wayland"]
|
||||
|
||||
`},
|
||||
{"valid short", state.Entries{testID: testState}, true, false, `8e2c76b0
|
||||
{"valid", state.Entries{testID: testState}, false, false, ` Instance PID Application Uptime
|
||||
8e2c76b0 3735928559 9 (org.chromium.Chromium) 1h2m32s
|
||||
`},
|
||||
{"valid short", state.Entries{testID: testState}, true, false, "8e2c76b0\n"},
|
||||
{"valid json", state.Entries{testID: testState}, false, true, `{
|
||||
"8e2c76b066dabe574cf073bdb46eb5c1": {
|
||||
"instance": [
|
||||
@@ -512,127 +496,127 @@ func Test_printPs(t *testing.T) {
|
||||
"pid": 3735928559,
|
||||
"config": {
|
||||
"id": "org.chromium.Chromium",
|
||||
"command": [
|
||||
"path": "/run/current-system/sw/bin/chromium",
|
||||
"args": [
|
||||
"chromium",
|
||||
"--ignore-gpu-blocklist",
|
||||
"--disable-smooth-scrolling",
|
||||
"--enable-features=UseOzonePlatform",
|
||||
"--ozone-platform=wayland"
|
||||
],
|
||||
"confinement": {
|
||||
"app_id": 9,
|
||||
"groups": [
|
||||
"video"
|
||||
"enablements": 13,
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.freedesktop.Notifications",
|
||||
"org.freedesktop.FileManager1",
|
||||
"org.freedesktop.ScreenSaver",
|
||||
"org.freedesktop.secrets",
|
||||
"org.kde.kwalletd5",
|
||||
"org.kde.kwalletd6",
|
||||
"org.gnome.SessionManager"
|
||||
],
|
||||
"username": "chronos",
|
||||
"home_inner": "/var/lib/fortify",
|
||||
"home": "/var/lib/persist/home/org.chromium.Chromium",
|
||||
"sandbox": {
|
||||
"hostname": "localhost",
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"dev": true,
|
||||
"syscall": {
|
||||
"compat": false,
|
||||
"deny_devel": true,
|
||||
"multiarch": true,
|
||||
"linux32": false,
|
||||
"can": false,
|
||||
"bluetooth": false
|
||||
},
|
||||
"no_new_session": true,
|
||||
"map_real_uid": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"filesystem": [
|
||||
{
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"override": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
"own": [
|
||||
"org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.chromium.*"
|
||||
],
|
||||
"call": {
|
||||
"org.freedesktop.portal.*": "*"
|
||||
},
|
||||
"extra_perms": [
|
||||
"broadcast": {
|
||||
"org.freedesktop.portal.*": "@/org/freedesktop/portal/*"
|
||||
},
|
||||
"filter": true
|
||||
},
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"username": "chronos",
|
||||
"shell": "/run/current-system/sw/bin/zsh",
|
||||
"data": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"dir": "/data/data/org.chromium.Chromium",
|
||||
"extra_perms": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/hakurei/u0",
|
||||
"x": true
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
}
|
||||
],
|
||||
"identity": 9,
|
||||
"groups": [
|
||||
"video",
|
||||
"dialout",
|
||||
"plugdev"
|
||||
],
|
||||
"container": {
|
||||
"hostname": "localhost",
|
||||
"wait_delay": -1,
|
||||
"seccomp_flags": 1,
|
||||
"seccomp_presets": 1,
|
||||
"seccomp_compat": true,
|
||||
"devel": true,
|
||||
"userns": true,
|
||||
"net": true,
|
||||
"tty": true,
|
||||
"multiarch": true,
|
||||
"env": {
|
||||
"GOOGLE_API_KEY": "AIzaSyBHDrl33hwRp4rMQY0ziRbj8K9LPA6vUCY",
|
||||
"GOOGLE_DEFAULT_CLIENT_ID": "77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT"
|
||||
},
|
||||
"map_real_uid": true,
|
||||
"device": true,
|
||||
"filesystem": [
|
||||
{
|
||||
"ensure": true,
|
||||
"path": "/var/lib/fortify/u0",
|
||||
"x": true
|
||||
"src": "/nix/store"
|
||||
},
|
||||
{
|
||||
"path": "/var/lib/fortify/u0/org.chromium.Chromium",
|
||||
"r": true,
|
||||
"w": true,
|
||||
"x": true
|
||||
"src": "/run/current-system"
|
||||
},
|
||||
{
|
||||
"src": "/run/opengl-driver"
|
||||
},
|
||||
{
|
||||
"src": "/var/db/nix-channels"
|
||||
},
|
||||
{
|
||||
"dst": "/data/data/org.chromium.Chromium",
|
||||
"src": "/var/lib/hakurei/u0/org.chromium.Chromium",
|
||||
"write": true,
|
||||
"require": true
|
||||
},
|
||||
{
|
||||
"src": "/dev/dri",
|
||||
"dev": true
|
||||
}
|
||||
],
|
||||
"system_bus": {
|
||||
"see": null,
|
||||
"talk": [
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower"
|
||||
],
|
||||
"own": null,
|
||||
"call": null,
|
||||
"broadcast": null,
|
||||
"filter": true
|
||||
},
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
"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
|
||||
},
|
||||
"enablements": 13
|
||||
"symlink": [
|
||||
[
|
||||
"/run/user/65534",
|
||||
"/run/user/150"
|
||||
]
|
||||
],
|
||||
"etc": "/etc",
|
||||
"auto_etc": true,
|
||||
"cover": [
|
||||
"/var/run/nscd"
|
||||
]
|
||||
}
|
||||
},
|
||||
"time": "1970-01-01T00:00:00.000000009Z"
|
||||
@@ -645,14 +629,8 @@ func Test_printPs(t *testing.T) {
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
{
|
||||
v := flagJSON
|
||||
t.Cleanup(func() { flagJSON = v })
|
||||
flagJSON = tc.json
|
||||
}
|
||||
|
||||
output := new(strings.Builder)
|
||||
printPs(output, testTime, stubStore(tc.entries), tc.short)
|
||||
printPs(output, testTime, stubStore(tc.entries), tc.short, tc.json)
|
||||
if got := output.String(); got != tc.want {
|
||||
t.Errorf("printPs: got\n%s\nwant\n%s",
|
||||
got, tc.want)
|
||||
@@ -13,22 +13,17 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
|
||||
fsuConfFile = "/etc/fsurc"
|
||||
envShim = "FORTIFY_SHIM"
|
||||
envAID = "FORTIFY_APP_ID"
|
||||
envGroups = "FORTIFY_GROUPS"
|
||||
hsuConfFile = "/etc/hsurc"
|
||||
envShim = "HAKUREI_SHIM"
|
||||
envAID = "HAKUREI_APP_ID"
|
||||
envGroups = "HAKUREI_GROUPS"
|
||||
|
||||
PR_SET_NO_NEW_PRIVS = 0x26
|
||||
)
|
||||
|
||||
var (
|
||||
Fmain = compPoison
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetFlags(0)
|
||||
log.SetPrefix("fsu: ")
|
||||
log.SetPrefix("hsu: ")
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
if os.Geteuid() != 0 {
|
||||
@@ -40,20 +35,16 @@ func main() {
|
||||
log.Fatal("this program must not be started by root")
|
||||
}
|
||||
|
||||
var fmain string
|
||||
if p, ok := checkPath(Fmain); !ok {
|
||||
log.Fatal("invalid fortify path, this copy of fsu is not compiled correctly")
|
||||
} else {
|
||||
fmain = p
|
||||
}
|
||||
|
||||
var toolPath string
|
||||
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")
|
||||
log.Fatal("hakurei executable has been deleted")
|
||||
} else if p != mustCheckPath(hmain) {
|
||||
log.Fatal("this program must be started by hakurei")
|
||||
} else {
|
||||
toolPath = p
|
||||
}
|
||||
|
||||
// uid = 1000000 +
|
||||
@@ -61,27 +52,27 @@ func main() {
|
||||
// aid
|
||||
uid := 1000000
|
||||
|
||||
// refuse to run if fsurc is not protected correctly
|
||||
if s, err := os.Stat(fsuConfFile); err != nil {
|
||||
// refuse to run if hsurc is not protected correctly
|
||||
if s, err := os.Stat(hsuConfFile); err != nil {
|
||||
log.Fatal(err)
|
||||
} else if s.Mode().Perm() != 0400 {
|
||||
log.Fatal("bad fsurc perm")
|
||||
log.Fatal("bad hsurc perm")
|
||||
} else if st := s.Sys().(*syscall.Stat_t); st.Uid != 0 || st.Gid != 0 {
|
||||
log.Fatal("fsurc must be owned by uid 0")
|
||||
log.Fatal("hsurc must be owned by uid 0")
|
||||
}
|
||||
|
||||
// authenticate before accepting user input
|
||||
if f, err := os.Open(fsuConfFile); err != nil {
|
||||
if f, err := os.Open(hsuConfFile); err != nil {
|
||||
log.Fatal(err)
|
||||
} else if fid, ok := mustParseConfig(f, puid); !ok {
|
||||
log.Fatalf("uid %d is not in the fsurc file", puid)
|
||||
log.Fatalf("uid %d is not in the hsurc 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")
|
||||
log.Fatal("HAKUREI_APP_ID not set")
|
||||
} else if aid, err := parseUint32Fast(as); err != nil || aid < 0 || aid > 9999 {
|
||||
log.Fatal("invalid aid")
|
||||
} else {
|
||||
@@ -91,12 +82,12 @@ func main() {
|
||||
// pass through setup fd to shim
|
||||
var shimSetupFd string
|
||||
if s, ok := os.LookupEnv(envShim); !ok {
|
||||
// fortify requests target uid
|
||||
// hakurei 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")
|
||||
log.Fatal("HAKUREI_SHIM holds an invalid value")
|
||||
} else {
|
||||
shimSetupFd = s
|
||||
}
|
||||
@@ -133,7 +124,7 @@ func main() {
|
||||
panic("uid out of bounds")
|
||||
}
|
||||
|
||||
// careful! users in the allowlist is effectively allowed to drop groups via fsu
|
||||
// careful! users in the allowlist is effectively allowed to drop groups via hsu
|
||||
|
||||
if err := syscall.Setresgid(uid, uid, uid); err != nil {
|
||||
log.Fatalf("cannot set gid: %v", err)
|
||||
@@ -147,13 +138,9 @@ func main() {
|
||||
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, PR_SET_NO_NEW_PRIVS, 1, 0); errno != 0 {
|
||||
log.Fatalf("cannot set no_new_privs flag: %s", errno.Error())
|
||||
}
|
||||
if err := syscall.Exec(fmain, []string{"fortify", "shim"}, []string{envShim + "=" + shimSetupFd}); err != nil {
|
||||
if err := syscall.Exec(toolPath, []string{"hakurei", "shim"}, []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)
|
||||
}
|
||||
23
cmd/hsu/package.nix
Normal file
23
cmd/hsu/package.nix
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
lib,
|
||||
buildGoModule,
|
||||
hakurei ? abort "hakurei package required",
|
||||
}:
|
||||
|
||||
buildGoModule {
|
||||
pname = "${hakurei.pname}-hsu";
|
||||
inherit (hakurei) version;
|
||||
|
||||
src = ./.;
|
||||
inherit (hakurei) vendorHash;
|
||||
env.CGO_ENABLED = 0;
|
||||
|
||||
preBuild = ''
|
||||
go mod init hsu >& /dev/null
|
||||
'';
|
||||
|
||||
ldflags = lib.attrsets.foldlAttrs (
|
||||
ldflags: name: value:
|
||||
ldflags ++ [ "-X main.${name}=${value}" ]
|
||||
) [ "-s -w" ] { hmain = "${hakurei}/libexec/hakurei"; };
|
||||
}
|
||||
@@ -50,7 +50,7 @@ func parseConfig(r io.Reader, puid int) (fid int, ok bool, err error) {
|
||||
if ok {
|
||||
// allowed fid range 0 to 99
|
||||
if fid, err = parseUint32Fast(lf[1]); err != nil || fid < 0 || fid > 99 {
|
||||
return -1, false, fmt.Errorf("invalid fortify uid on line %d", line)
|
||||
return -1, false, fmt.Errorf("invalid identity on line %d", line)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -65,7 +65,7 @@ func Test_parseConfig(t *testing.T) {
|
||||
{"empty", 0, -1, "", ``},
|
||||
{"invalid field", 0, -1, "invalid entry on line 1", `9`},
|
||||
{"invalid puid", 0, -1, "invalid parent uid on line 1", `f 9`},
|
||||
{"invalid fid", 1000, -1, "invalid fortify uid on line 1", `1000 f`},
|
||||
{"invalid fid", 1000, -1, "invalid identity on line 1", `1000 f`},
|
||||
{"match", 1000, 0, "", `1000 0`},
|
||||
}
|
||||
|
||||
20
cmd/hsu/path.go
Normal file
20
cmd/hsu/path.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"path"
|
||||
)
|
||||
|
||||
const compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
|
||||
|
||||
var (
|
||||
hmain = compPoison
|
||||
)
|
||||
|
||||
func mustCheckPath(p string) string {
|
||||
if p != compPoison && p != "" && path.IsAbs(p) {
|
||||
return p
|
||||
}
|
||||
log.Fatal("this program is compiled incorrectly")
|
||||
return compPoison
|
||||
}
|
||||
154
cmd/planterette/app.go
Normal file
154
cmd/planterette/app.go
Normal file
@@ -0,0 +1,154 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/system"
|
||||
"hakurei.app/system/dbus"
|
||||
)
|
||||
|
||||
type appInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
|
||||
// passed through to [hst.Config]
|
||||
ID string `json:"id"`
|
||||
// passed through to [hst.Config]
|
||||
Identity int `json:"identity"`
|
||||
// passed through to [hst.Config]
|
||||
Groups []string `json:"groups,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Devel bool `json:"devel,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Userns bool `json:"userns,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Net bool `json:"net,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Device bool `json:"dev,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Tty bool `json:"tty,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
MapRealUID bool `json:"map_real_uid,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
DirectWayland bool `json:"direct_wayland,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
SystemBus *dbus.Config `json:"system_bus,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
SessionBus *dbus.Config `json:"session_bus,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Enablements system.Enablement `json:"enablements"`
|
||||
|
||||
// passed through to [hst.Config]
|
||||
Multiarch bool `json:"multiarch,omitempty"`
|
||||
// passed through to [hst.Config]
|
||||
Bluetooth bool `json:"bluetooth,omitempty"`
|
||||
|
||||
// allow gpu access within sandbox
|
||||
GPU bool `json:"gpu"`
|
||||
// store path to nixGL mesa wrappers
|
||||
Mesa string `json:"mesa,omitempty"`
|
||||
// store path to nixGL source
|
||||
NixGL string `json:"nix_gl,omitempty"`
|
||||
// store path to activate-and-exec script
|
||||
Launcher string `json:"launcher"`
|
||||
// store path to /run/current-system
|
||||
CurrentSystem string `json:"current_system"`
|
||||
// store path to home-manager activation package
|
||||
ActivationPackage string `json:"activation_package"`
|
||||
}
|
||||
|
||||
func (app *appInfo) toFst(pathSet *appPathSet, argv []string, flagDropShell bool) *hst.Config {
|
||||
config := &hst.Config{
|
||||
ID: app.ID,
|
||||
|
||||
Path: argv[0],
|
||||
Args: argv,
|
||||
|
||||
Enablements: app.Enablements,
|
||||
|
||||
SystemBus: app.SystemBus,
|
||||
SessionBus: app.SessionBus,
|
||||
DirectWayland: app.DirectWayland,
|
||||
|
||||
Username: "hakurei",
|
||||
Shell: shellPath,
|
||||
Data: pathSet.homeDir,
|
||||
Dir: path.Join("/data/data", app.ID),
|
||||
|
||||
Identity: app.Identity,
|
||||
Groups: app.Groups,
|
||||
|
||||
Container: &hst.ContainerConfig{
|
||||
Hostname: formatHostname(app.Name),
|
||||
Devel: app.Devel,
|
||||
Userns: app.Userns,
|
||||
Net: app.Net,
|
||||
Device: app.Device,
|
||||
Tty: app.Tty || flagDropShell,
|
||||
MapRealUID: app.MapRealUID,
|
||||
Filesystem: []*hst.FilesystemConfig{
|
||||
{Src: path.Join(pathSet.nixPath, "store"), Dst: "/nix/store", Must: true},
|
||||
{Src: pathSet.metaPath, Dst: path.Join(hst.Tmp, "app"), Must: true},
|
||||
{Src: "/etc/resolv.conf"},
|
||||
{Src: "/sys/block"},
|
||||
{Src: "/sys/bus"},
|
||||
{Src: "/sys/class"},
|
||||
{Src: "/sys/dev"},
|
||||
{Src: "/sys/devices"},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(pathSet.cacheDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
ExtraPerms: []*hst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
},
|
||||
}
|
||||
if app.Multiarch {
|
||||
config.Container.SeccompFlags |= seccomp.AllowMultiarch
|
||||
}
|
||||
if app.Bluetooth {
|
||||
config.Container.SeccompFlags |= seccomp.AllowBluetooth
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
func loadAppInfo(name string, beforeFail func()) *appInfo {
|
||||
bundle := new(appInfo)
|
||||
if f, err := os.Open(name); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot open bundle: %v", err)
|
||||
} else if err = json.NewDecoder(f).Decode(&bundle); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot parse bundle metadata: %v", err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
log.Printf("cannot close bundle metadata: %v", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
if bundle.ID == "" {
|
||||
beforeFail()
|
||||
log.Fatal("application identifier must not be empty")
|
||||
}
|
||||
|
||||
return bundle
|
||||
}
|
||||
|
||||
func formatHostname(name string) string {
|
||||
if h, err := os.Hostname(); err != nil {
|
||||
log.Printf("cannot get hostname: %v", err)
|
||||
return "hakurei-" + name
|
||||
} else {
|
||||
return h + "-" + name
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
{
|
||||
lib,
|
||||
stdenv,
|
||||
closureInfo,
|
||||
writeScript,
|
||||
runtimeShell,
|
||||
writeText,
|
||||
@@ -15,18 +17,21 @@
|
||||
runCommand,
|
||||
fetchFromGitHub,
|
||||
|
||||
zstd,
|
||||
nix,
|
||||
sqlite,
|
||||
|
||||
name ? throw "name is required",
|
||||
version ? throw "version is required",
|
||||
pname ? "${name}-${version}",
|
||||
modules ? [ ],
|
||||
nixosModules ? [ ],
|
||||
script ? ''
|
||||
exec "$SHELL" "$@"
|
||||
'',
|
||||
|
||||
id ? name,
|
||||
app_id ? throw "app_id is required",
|
||||
identity ? throw "identity is required",
|
||||
groups ? [ ],
|
||||
userns ? false,
|
||||
net ? true,
|
||||
@@ -52,7 +57,7 @@ let
|
||||
modules = modules ++ [
|
||||
{
|
||||
home = {
|
||||
username = "fortify";
|
||||
username = "hakurei";
|
||||
homeDirectory = "/data/data/${id}";
|
||||
stateVersion = "22.11";
|
||||
};
|
||||
@@ -60,7 +65,7 @@ let
|
||||
];
|
||||
};
|
||||
|
||||
launcher = writeScript "fortify-${pname}" ''
|
||||
launcher = writeScript "hakurei-${pname}" ''
|
||||
#!${runtimeShell} -el
|
||||
${script}
|
||||
'';
|
||||
@@ -72,6 +77,8 @@ let
|
||||
etc.nixpkgs.source = nixpkgs.outPath;
|
||||
systemPackages = [ pkgs.nix ];
|
||||
};
|
||||
|
||||
imports = nixosModules;
|
||||
};
|
||||
nixos = nixpkgs.lib.nixosSystem {
|
||||
inherit system;
|
||||
@@ -140,7 +147,7 @@ let
|
||||
name
|
||||
version
|
||||
id
|
||||
app_id
|
||||
identity
|
||||
launcher
|
||||
groups
|
||||
userns
|
||||
@@ -164,11 +171,7 @@ let
|
||||
broadcast = { };
|
||||
});
|
||||
|
||||
enablements =
|
||||
(if allow_wayland then 1 else 0)
|
||||
+ (if allow_x11 then 2 else 0)
|
||||
+ (if allow_dbus then 4 else 0)
|
||||
+ (if allow_pulse then 8 else 0);
|
||||
enablements = (if allow_wayland then 1 else 0) + (if allow_x11 then 2 else 0) + (if allow_dbus then 4 else 0) + (if allow_pulse then 8 else 0);
|
||||
|
||||
mesa = if gpu then mesaWrappers else null;
|
||||
nix_gl = if gpu then nixGL else null;
|
||||
@@ -177,26 +180,72 @@ let
|
||||
};
|
||||
in
|
||||
|
||||
writeScript "fortify-${pname}-bundle-prelude" ''
|
||||
#!${runtimeShell} -el
|
||||
OUT="$(mktemp -d)"
|
||||
TAR="$(mktemp -u)"
|
||||
set -x
|
||||
stdenv.mkDerivation {
|
||||
name = "${pname}.pkg";
|
||||
inherit version;
|
||||
__structuredAttrs = true;
|
||||
|
||||
nix copy --no-check-sigs --to "$OUT" "${nix}" "${nixos.config.system.build.toplevel}"
|
||||
nix store --store "$OUT" optimise
|
||||
chmod -R +r "$OUT/nix/var"
|
||||
nix copy --no-check-sigs --to "file://$OUT/res?compression=zstd&compression-level=19¶llel-compression=true" \
|
||||
"${homeManagerConfiguration.activationPackage}" \
|
||||
"${launcher}" ${if gpu then "${mesaWrappers} ${nixGL}" else ""}
|
||||
mkdir -p "$OUT/etc"
|
||||
tar -C "$OUT/etc" -xf "${etc}/etc.tar"
|
||||
cp "${writeText "bundle.json" info}" "$OUT/bundle.json"
|
||||
nativeBuildInputs = [
|
||||
zstd
|
||||
nix
|
||||
sqlite
|
||||
];
|
||||
|
||||
# creating an intermediate file improves zstd performance
|
||||
tar -C "$OUT" -cf "$TAR" .
|
||||
chmod +w -R "$OUT" && rm -rf "$OUT"
|
||||
buildCommand = ''
|
||||
NIX_ROOT="$(mktemp -d)"
|
||||
export USER="nobody"
|
||||
|
||||
zstd -T0 -19 -fo "${pname}.pkg" "$TAR"
|
||||
rm "$TAR"
|
||||
''
|
||||
# create bootstrap store
|
||||
bootstrapClosureInfo="${
|
||||
closureInfo {
|
||||
rootPaths = [
|
||||
nix
|
||||
nixos.config.system.build.toplevel
|
||||
];
|
||||
}
|
||||
}"
|
||||
echo "copying bootstrap store paths..."
|
||||
mkdir -p "$NIX_ROOT/nix/store"
|
||||
xargs -n 1 -a "$bootstrapClosureInfo/store-paths" cp -at "$NIX_ROOT/nix/store/"
|
||||
NIX_REMOTE="local?root=$NIX_ROOT" nix-store --load-db < "$bootstrapClosureInfo/registration"
|
||||
NIX_REMOTE="local?root=$NIX_ROOT" nix-store --optimise
|
||||
sqlite3 "$NIX_ROOT/nix/var/nix/db/db.sqlite" "UPDATE ValidPaths SET registrationTime = ''${SOURCE_DATE_EPOCH}"
|
||||
chmod -R +r "$NIX_ROOT/nix/var"
|
||||
|
||||
# create binary cache
|
||||
closureInfo="${
|
||||
closureInfo {
|
||||
rootPaths = [
|
||||
homeManagerConfiguration.activationPackage
|
||||
launcher
|
||||
]
|
||||
++ optionals gpu [
|
||||
mesaWrappers
|
||||
nixGL
|
||||
];
|
||||
}
|
||||
}"
|
||||
echo "copying application paths..."
|
||||
TMP_STORE="$(mktemp -d)"
|
||||
mkdir -p "$TMP_STORE/nix/store"
|
||||
xargs -n 1 -a "$closureInfo/store-paths" cp -at "$TMP_STORE/nix/store/"
|
||||
NIX_REMOTE="local?root=$TMP_STORE" nix-store --load-db < "$closureInfo/registration"
|
||||
sqlite3 "$TMP_STORE/nix/var/nix/db/db.sqlite" "UPDATE ValidPaths SET registrationTime = ''${SOURCE_DATE_EPOCH}"
|
||||
NIX_REMOTE="local?root=$TMP_STORE" nix --offline --extra-experimental-features nix-command \
|
||||
--verbose --log-format raw-with-logs \
|
||||
copy --all --no-check-sigs --to \
|
||||
"file://$NIX_ROOT/res?compression=zstd&compression-level=19¶llel-compression=true"
|
||||
|
||||
# package /etc
|
||||
mkdir -p "$NIX_ROOT/etc"
|
||||
tar -C "$NIX_ROOT/etc" -xf "${etc}/etc.tar"
|
||||
|
||||
# write metadata
|
||||
cp "${writeText "bundle.json" info}" "$NIX_ROOT/bundle.json"
|
||||
|
||||
# create an intermediate file to improve zstd performance
|
||||
INTER="$(mktemp)"
|
||||
tar -C "$NIX_ROOT" -cf "$INTER" .
|
||||
zstd -T0 -19 -fo "$out" "$INTER"
|
||||
'';
|
||||
}
|
||||
333
cmd/planterette/main.go
Normal file
333
cmd/planterette/main.go
Normal file
@@ -0,0 +1,333 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"syscall"
|
||||
|
||||
"hakurei.app/command"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/hlog"
|
||||
)
|
||||
|
||||
const shellPath = "/run/current-system/sw/bin/bash"
|
||||
|
||||
var (
|
||||
errSuccess = errors.New("success")
|
||||
)
|
||||
|
||||
func init() {
|
||||
hlog.Prepare("planterette")
|
||||
if err := os.Setenv("SHELL", shellPath); err != nil {
|
||||
log.Fatalf("cannot set $SHELL: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if os.Geteuid() == 0 {
|
||||
log.Fatal("this program must not run as root")
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(),
|
||||
syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop() // unreachable
|
||||
|
||||
var (
|
||||
flagVerbose bool
|
||||
flagDropShell bool
|
||||
)
|
||||
c := command.New(os.Stderr, log.Printf, "planterette", func([]string) error { internal.InstallOutput(flagVerbose); return nil }).
|
||||
Flag(&flagVerbose, "v", command.BoolFlag(false), "Print debug messages to the console").
|
||||
Flag(&flagDropShell, "s", command.BoolFlag(false), "Drop to a shell in place of next hakurei action")
|
||||
|
||||
{
|
||||
var (
|
||||
flagDropShellActivate bool
|
||||
)
|
||||
c.NewCommand("install", "Install an application from its package", func(args []string) error {
|
||||
if len(args) != 1 {
|
||||
log.Println("invalid argument")
|
||||
return syscall.EINVAL
|
||||
}
|
||||
pkgPath := args[0]
|
||||
if !path.IsAbs(pkgPath) {
|
||||
if dir, err := os.Getwd(); err != nil {
|
||||
log.Printf("cannot get current directory: %v", err)
|
||||
return err
|
||||
} else {
|
||||
pkgPath = path.Join(dir, pkgPath)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Look up paths to programs started by planterette.
|
||||
This is done here to ease error handling as cleanup is not yet required.
|
||||
*/
|
||||
|
||||
var (
|
||||
_ = lookPath("zstd")
|
||||
tar = lookPath("tar")
|
||||
chmod = lookPath("chmod")
|
||||
rm = lookPath("rm")
|
||||
)
|
||||
|
||||
/*
|
||||
Extract package and set up for cleanup.
|
||||
*/
|
||||
|
||||
var workDir string
|
||||
if p, err := os.MkdirTemp("", "planterette.*"); err != nil {
|
||||
log.Printf("cannot create temporary directory: %v", err)
|
||||
return err
|
||||
} else {
|
||||
workDir = p
|
||||
}
|
||||
cleanup := func() {
|
||||
// should be faster than a native implementation
|
||||
mustRun(chmod, "-R", "+w", workDir)
|
||||
mustRun(rm, "-rf", workDir)
|
||||
}
|
||||
beforeRunFail.Store(&cleanup)
|
||||
|
||||
mustRun(tar, "-C", workDir, "-xf", pkgPath)
|
||||
|
||||
/*
|
||||
Parse bundle and app metadata, do pre-install checks.
|
||||
*/
|
||||
|
||||
bundle := loadAppInfo(path.Join(workDir, "bundle.json"), cleanup)
|
||||
pathSet := pathSetByApp(bundle.ID)
|
||||
|
||||
a := bundle
|
||||
if s, err := os.Stat(pathSet.metaPath); err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
cleanup()
|
||||
log.Printf("cannot access %q: %v", pathSet.metaPath, err)
|
||||
return err
|
||||
}
|
||||
// did not modify app, clean installation condition met later
|
||||
} else if s.IsDir() {
|
||||
cleanup()
|
||||
log.Printf("metadata path %q is not a file", pathSet.metaPath)
|
||||
return syscall.EBADMSG
|
||||
} else {
|
||||
a = loadAppInfo(pathSet.metaPath, cleanup)
|
||||
if a.ID != bundle.ID {
|
||||
cleanup()
|
||||
log.Printf("app %q claims to have identifier %q",
|
||||
bundle.ID, a.ID)
|
||||
return syscall.EBADE
|
||||
}
|
||||
// sec: should verify credentials
|
||||
}
|
||||
|
||||
if a != bundle {
|
||||
// do not try to re-install
|
||||
if a.NixGL == bundle.NixGL &&
|
||||
a.CurrentSystem == bundle.CurrentSystem &&
|
||||
a.Launcher == bundle.Launcher &&
|
||||
a.ActivationPackage == bundle.ActivationPackage {
|
||||
cleanup()
|
||||
log.Printf("package %q is identical to local application %q",
|
||||
pkgPath, a.ID)
|
||||
return errSuccess
|
||||
}
|
||||
|
||||
// identity determines uid
|
||||
if a.Identity != bundle.Identity {
|
||||
cleanup()
|
||||
log.Printf("package %q identity %d differs from installed %d",
|
||||
pkgPath, bundle.Identity, a.Identity)
|
||||
return syscall.EBADE
|
||||
}
|
||||
|
||||
// sec: should compare version string
|
||||
hlog.Verbosef("installing application %q version %q over local %q",
|
||||
bundle.ID, bundle.Version, a.Version)
|
||||
} else {
|
||||
hlog.Verbosef("application %q clean installation", bundle.ID)
|
||||
// sec: should install credentials
|
||||
}
|
||||
|
||||
/*
|
||||
Setup steps for files owned by the target user.
|
||||
*/
|
||||
|
||||
withCacheDir(ctx, "install", []string{
|
||||
// export inner bundle path in the environment
|
||||
"export BUNDLE=" + hst.Tmp + "/bundle",
|
||||
// replace inner /etc
|
||||
"mkdir -p etc",
|
||||
"chmod -R +w etc",
|
||||
"rm -rf etc",
|
||||
"cp -dRf $BUNDLE/etc etc",
|
||||
// replace inner /nix
|
||||
"mkdir -p nix",
|
||||
"chmod -R +w nix",
|
||||
"rm -rf nix",
|
||||
"cp -dRf /nix nix",
|
||||
// copy from binary cache
|
||||
"nix copy --offline --no-check-sigs --all --from file://$BUNDLE/res --to $PWD",
|
||||
// deduplicate nix store
|
||||
"nix store --offline --store $PWD optimise",
|
||||
// make cache directory world-readable for autoetc
|
||||
"chmod 0755 .",
|
||||
}, workDir, bundle, pathSet, flagDropShell, cleanup)
|
||||
|
||||
if bundle.GPU {
|
||||
withCacheDir(ctx, "mesa-wrappers", []string{
|
||||
// link nixGL mesa wrappers
|
||||
"mkdir -p nix/.nixGL",
|
||||
"ln -s " + bundle.Mesa + "/bin/nixGLIntel nix/.nixGL/nixGL",
|
||||
"ln -s " + bundle.Mesa + "/bin/nixVulkanIntel nix/.nixGL/nixVulkan",
|
||||
}, workDir, bundle, pathSet, false, cleanup)
|
||||
}
|
||||
|
||||
/*
|
||||
Activate home-manager generation.
|
||||
*/
|
||||
|
||||
withNixDaemon(ctx, "activate", []string{
|
||||
// clean up broken links
|
||||
"mkdir -p .local/state/{nix,home-manager}",
|
||||
"chmod -R +w .local/state/{nix,home-manager}",
|
||||
"rm -rf .local/state/{nix,home-manager}",
|
||||
// run activation script
|
||||
bundle.ActivationPackage + "/activate",
|
||||
}, false, func(config *hst.Config) *hst.Config { return config },
|
||||
bundle, pathSet, flagDropShellActivate, cleanup)
|
||||
|
||||
/*
|
||||
Installation complete. Write metadata to block re-installs or downgrades.
|
||||
*/
|
||||
|
||||
// serialise metadata to ensure consistency
|
||||
if f, err := os.OpenFile(pathSet.metaPath+"~", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644); err != nil {
|
||||
cleanup()
|
||||
log.Printf("cannot create metadata file: %v", err)
|
||||
return err
|
||||
} else if err = json.NewEncoder(f).Encode(bundle); err != nil {
|
||||
cleanup()
|
||||
log.Printf("cannot write metadata: %v", err)
|
||||
return err
|
||||
} else if err = f.Close(); err != nil {
|
||||
log.Printf("cannot close metadata file: %v", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
if err := os.Rename(pathSet.metaPath+"~", pathSet.metaPath); err != nil {
|
||||
cleanup()
|
||||
log.Printf("cannot rename metadata file: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
cleanup()
|
||||
return errSuccess
|
||||
}).
|
||||
Flag(&flagDropShellActivate, "s", command.BoolFlag(false), "Drop to a shell on activation")
|
||||
}
|
||||
|
||||
{
|
||||
var (
|
||||
flagDropShellNixGL bool
|
||||
flagAutoDrivers bool
|
||||
)
|
||||
c.NewCommand("start", "Start an application", func(args []string) error {
|
||||
if len(args) < 1 {
|
||||
log.Println("invalid argument")
|
||||
return syscall.EINVAL
|
||||
}
|
||||
|
||||
/*
|
||||
Parse app metadata.
|
||||
*/
|
||||
|
||||
id := args[0]
|
||||
pathSet := pathSetByApp(id)
|
||||
a := loadAppInfo(pathSet.metaPath, func() {})
|
||||
if a.ID != id {
|
||||
log.Printf("app %q claims to have identifier %q", id, a.ID)
|
||||
return syscall.EBADE
|
||||
}
|
||||
|
||||
/*
|
||||
Prepare nixGL.
|
||||
*/
|
||||
|
||||
if a.GPU && flagAutoDrivers {
|
||||
withNixDaemon(ctx, "nix-gl", []string{
|
||||
"mkdir -p /nix/.nixGL/auto",
|
||||
"rm -rf /nix/.nixGL/auto",
|
||||
"export NIXPKGS_ALLOW_UNFREE=1",
|
||||
"nix build --impure " +
|
||||
"--out-link /nix/.nixGL/auto/opengl " +
|
||||
"--override-input nixpkgs path:/etc/nixpkgs " +
|
||||
"path:" + a.NixGL,
|
||||
"nix build --impure " +
|
||||
"--out-link /nix/.nixGL/auto/vulkan " +
|
||||
"--override-input nixpkgs path:/etc/nixpkgs " +
|
||||
"path:" + a.NixGL + "#nixVulkanNvidia",
|
||||
}, true, func(config *hst.Config) *hst.Config {
|
||||
config.Container.Filesystem = append(config.Container.Filesystem, []*hst.FilesystemConfig{
|
||||
{Src: "/etc/resolv.conf"},
|
||||
{Src: "/sys/block"},
|
||||
{Src: "/sys/bus"},
|
||||
{Src: "/sys/class"},
|
||||
{Src: "/sys/dev"},
|
||||
{Src: "/sys/devices"},
|
||||
}...)
|
||||
appendGPUFilesystem(config)
|
||||
return config
|
||||
}, a, pathSet, flagDropShellNixGL, func() {})
|
||||
}
|
||||
|
||||
/*
|
||||
Create app configuration.
|
||||
*/
|
||||
|
||||
argv := make([]string, 1, len(args))
|
||||
if !flagDropShell {
|
||||
argv[0] = a.Launcher
|
||||
} else {
|
||||
argv[0] = shellPath
|
||||
}
|
||||
argv = append(argv, args[1:]...)
|
||||
|
||||
config := a.toFst(pathSet, argv, flagDropShell)
|
||||
|
||||
/*
|
||||
Expose GPU devices.
|
||||
*/
|
||||
|
||||
if a.GPU {
|
||||
config.Container.Filesystem = append(config.Container.Filesystem,
|
||||
&hst.FilesystemConfig{Src: path.Join(pathSet.nixPath, ".nixGL"), Dst: path.Join(hst.Tmp, "nixGL")})
|
||||
appendGPUFilesystem(config)
|
||||
}
|
||||
|
||||
/*
|
||||
Spawn app.
|
||||
*/
|
||||
|
||||
mustRunApp(ctx, config, func() {})
|
||||
return errSuccess
|
||||
}).
|
||||
Flag(&flagDropShellNixGL, "s", command.BoolFlag(false), "Drop to a shell on nixGL build").
|
||||
Flag(&flagAutoDrivers, "auto-drivers", command.BoolFlag(false), "Attempt automatic opengl driver detection")
|
||||
}
|
||||
|
||||
c.MustParse(os.Args[1:], func(err error) {
|
||||
hlog.Verbosef("command returned %v", err)
|
||||
if errors.Is(err, errSuccess) {
|
||||
hlog.BeforeExit()
|
||||
os.Exit(0)
|
||||
}
|
||||
})
|
||||
log.Fatal("unreachable")
|
||||
}
|
||||
101
cmd/planterette/paths.go
Normal file
101
cmd/planterette/paths.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/hlog"
|
||||
)
|
||||
|
||||
var (
|
||||
dataHome string
|
||||
)
|
||||
|
||||
func init() {
|
||||
// dataHome
|
||||
if p, ok := os.LookupEnv("HAKUREI_DATA_HOME"); ok {
|
||||
dataHome = p
|
||||
} else {
|
||||
dataHome = "/var/lib/hakurei/" + strconv.Itoa(os.Getuid())
|
||||
}
|
||||
}
|
||||
|
||||
func lookPath(file string) string {
|
||||
if p, err := exec.LookPath(file); err != nil {
|
||||
log.Fatalf("%s: command not found", file)
|
||||
return ""
|
||||
} else {
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
var beforeRunFail = new(atomic.Pointer[func()])
|
||||
|
||||
func mustRun(name string, arg ...string) {
|
||||
hlog.Verbosef("spawning process: %q %q", name, arg)
|
||||
cmd := exec.Command(name, arg...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
if f := beforeRunFail.Swap(nil); f != nil {
|
||||
(*f)()
|
||||
}
|
||||
log.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
type appPathSet struct {
|
||||
// ${dataHome}/${id}
|
||||
baseDir string
|
||||
// ${baseDir}/app
|
||||
metaPath string
|
||||
// ${baseDir}/files
|
||||
homeDir string
|
||||
// ${baseDir}/cache
|
||||
cacheDir string
|
||||
// ${baseDir}/cache/nix
|
||||
nixPath string
|
||||
}
|
||||
|
||||
func pathSetByApp(id string) *appPathSet {
|
||||
pathSet := new(appPathSet)
|
||||
pathSet.baseDir = path.Join(dataHome, id)
|
||||
pathSet.metaPath = path.Join(pathSet.baseDir, "app")
|
||||
pathSet.homeDir = path.Join(pathSet.baseDir, "files")
|
||||
pathSet.cacheDir = path.Join(pathSet.baseDir, "cache")
|
||||
pathSet.nixPath = path.Join(pathSet.cacheDir, "nix")
|
||||
return pathSet
|
||||
}
|
||||
|
||||
func appendGPUFilesystem(config *hst.Config) {
|
||||
config.Container.Filesystem = append(config.Container.Filesystem, []*hst.FilesystemConfig{
|
||||
// flatpak commit 763a686d874dd668f0236f911de00b80766ffe79
|
||||
{Src: "/dev/dri", Device: true},
|
||||
// mali
|
||||
{Src: "/dev/mali", Device: true},
|
||||
{Src: "/dev/mali0", Device: true},
|
||||
{Src: "/dev/umplock", Device: true},
|
||||
// nvidia
|
||||
{Src: "/dev/nvidiactl", Device: true},
|
||||
{Src: "/dev/nvidia-modeset", Device: true},
|
||||
// nvidia OpenCL/CUDA
|
||||
{Src: "/dev/nvidia-uvm", Device: true},
|
||||
{Src: "/dev/nvidia-uvm-tools", Device: true},
|
||||
|
||||
// flatpak commit d2dff2875bb3b7e2cd92d8204088d743fd07f3ff
|
||||
{Src: "/dev/nvidia0", Device: true}, {Src: "/dev/nvidia1", Device: true},
|
||||
{Src: "/dev/nvidia2", Device: true}, {Src: "/dev/nvidia3", Device: true},
|
||||
{Src: "/dev/nvidia4", Device: true}, {Src: "/dev/nvidia5", Device: true},
|
||||
{Src: "/dev/nvidia6", Device: true}, {Src: "/dev/nvidia7", Device: true},
|
||||
{Src: "/dev/nvidia8", Device: true}, {Src: "/dev/nvidia9", Device: true},
|
||||
{Src: "/dev/nvidia10", Device: true}, {Src: "/dev/nvidia11", Device: true},
|
||||
{Src: "/dev/nvidia12", Device: true}, {Src: "/dev/nvidia13", Device: true},
|
||||
{Src: "/dev/nvidia14", Device: true}, {Src: "/dev/nvidia15", Device: true},
|
||||
{Src: "/dev/nvidia16", Device: true}, {Src: "/dev/nvidia17", Device: true},
|
||||
{Src: "/dev/nvidia18", Device: true}, {Src: "/dev/nvidia19", Device: true},
|
||||
}...)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
@@ -8,33 +9,27 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/hlog"
|
||||
)
|
||||
|
||||
const compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
|
||||
var hakureiPath = internal.MustHakureiPath()
|
||||
|
||||
var (
|
||||
Fmain = compPoison
|
||||
)
|
||||
|
||||
func fortifyApp(config *fst.Config, beforeFail func()) {
|
||||
func mustRunApp(ctx context.Context, config *hst.Config, beforeFail func()) {
|
||||
var (
|
||||
cmd *exec.Cmd
|
||||
st io.WriteCloser
|
||||
)
|
||||
if p, ok := internal.Path(Fmain); !ok {
|
||||
beforeFail()
|
||||
log.Fatal("invalid fortify path, this copy of fpkg is not compiled correctly")
|
||||
} else if r, w, err := os.Pipe(); err != nil {
|
||||
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot pipe: %v", err)
|
||||
} else {
|
||||
if fmsg.Load() {
|
||||
cmd = exec.Command(p, "-v", "app", "3")
|
||||
if hlog.Load() {
|
||||
cmd = exec.CommandContext(ctx, hakureiPath, "-v", "app", "3")
|
||||
} else {
|
||||
cmd = exec.Command(p, "app", "3")
|
||||
cmd = exec.CommandContext(ctx, hakureiPath, "app", "3")
|
||||
}
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
cmd.ExtraFiles = []*os.File{r}
|
||||
@@ -50,7 +45,7 @@ func fortifyApp(config *fst.Config, beforeFail func()) {
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
beforeFail()
|
||||
log.Fatalf("cannot start fortify: %v", err)
|
||||
log.Fatalf("cannot start hakurei: %v", err)
|
||||
}
|
||||
if err := cmd.Wait(); err != nil {
|
||||
var exitError *exec.ExitError
|
||||
62
cmd/planterette/test/configuration.nix
Normal file
62
cmd/planterette/test/configuration.nix
Normal file
@@ -0,0 +1,62 @@
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
users.users = {
|
||||
alice = {
|
||||
isNormalUser = true;
|
||||
description = "Alice Foobar";
|
||||
password = "foobar";
|
||||
uid = 1000;
|
||||
};
|
||||
};
|
||||
|
||||
home-manager.users.alice.home.stateVersion = "24.11";
|
||||
|
||||
# Automatically login on tty1 as a normal user:
|
||||
services.getty.autologinUser = "alice";
|
||||
|
||||
environment = {
|
||||
variables = {
|
||||
SWAYSOCK = "/tmp/sway-ipc.sock";
|
||||
WLR_RENDERER = "pixman";
|
||||
};
|
||||
};
|
||||
|
||||
# Automatically configure and start Sway when logging in on tty1:
|
||||
programs.bash.loginShellInit = ''
|
||||
if [ "$(tty)" = "/dev/tty1" ]; then
|
||||
set -e
|
||||
|
||||
mkdir -p ~/.config/sway
|
||||
(sed s/Mod4/Mod1/ /etc/sway/config &&
|
||||
echo 'output * bg ${pkgs.nixos-artwork.wallpapers.simple-light-gray.gnomeFilePath} fill' &&
|
||||
echo 'output Virtual-1 res 1680x1050') > ~/.config/sway/config
|
||||
|
||||
sway --validate
|
||||
systemd-cat --identifier=session sway && touch /tmp/sway-exit-ok
|
||||
fi
|
||||
'';
|
||||
|
||||
programs.sway.enable = true;
|
||||
|
||||
virtualisation = {
|
||||
diskSize = 6 * 1024;
|
||||
|
||||
qemu.options = [
|
||||
# Need to switch to a different GPU driver than the default one (-vga std) so that Sway can launch:
|
||||
"-vga none -device virtio-gpu-pci"
|
||||
|
||||
# Increase zstd performance:
|
||||
"-smp 8"
|
||||
];
|
||||
};
|
||||
|
||||
environment.hakurei = {
|
||||
enable = true;
|
||||
stateDir = "/var/lib/hakurei";
|
||||
users.alice = 0;
|
||||
|
||||
extraHomeConfig = {
|
||||
home.stateVersion = "23.05";
|
||||
};
|
||||
};
|
||||
}
|
||||
34
cmd/planterette/test/default.nix
Normal file
34
cmd/planterette/test/default.nix
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
nixosTest,
|
||||
callPackage,
|
||||
|
||||
system,
|
||||
self,
|
||||
}:
|
||||
let
|
||||
buildPackage = self.buildPackage.${system};
|
||||
in
|
||||
nixosTest {
|
||||
name = "planterette";
|
||||
nodes.machine = {
|
||||
environment.etc = {
|
||||
"foot.pkg".source = callPackage ./foot.nix { inherit buildPackage; };
|
||||
};
|
||||
|
||||
imports = [
|
||||
./configuration.nix
|
||||
|
||||
self.nixosModules.hakurei
|
||||
self.inputs.home-manager.nixosModules.home-manager
|
||||
];
|
||||
};
|
||||
|
||||
# adapted from nixos sway integration tests
|
||||
|
||||
# testScriptWithTypes:49: error: Cannot call function of unknown type
|
||||
# (machine.succeed if succeed else machine.execute)(
|
||||
# ^
|
||||
# Found 1 error in 1 file (checked 1 source file)
|
||||
skipTypeCheck = true;
|
||||
testScript = builtins.readFile ./test.py;
|
||||
}
|
||||
48
cmd/planterette/test/foot.nix
Normal file
48
cmd/planterette/test/foot.nix
Normal file
@@ -0,0 +1,48 @@
|
||||
{
|
||||
lib,
|
||||
buildPackage,
|
||||
foot,
|
||||
wayland-utils,
|
||||
inconsolata,
|
||||
}:
|
||||
|
||||
buildPackage {
|
||||
name = "foot";
|
||||
inherit (foot) version;
|
||||
|
||||
identity = 2;
|
||||
id = "org.codeberg.dnkl.foot";
|
||||
|
||||
modules = [
|
||||
{
|
||||
home.packages = [
|
||||
foot
|
||||
|
||||
# For wayland-info:
|
||||
wayland-utils
|
||||
];
|
||||
}
|
||||
];
|
||||
|
||||
nixosModules = [
|
||||
{
|
||||
# To help with OCR:
|
||||
environment.etc."xdg/foot/foot.ini".text = lib.generators.toINI { } {
|
||||
main = {
|
||||
font = "inconsolata:size=14";
|
||||
};
|
||||
colors = rec {
|
||||
foreground = "000000";
|
||||
background = "ffffff";
|
||||
regular2 = foreground;
|
||||
};
|
||||
};
|
||||
|
||||
fonts.packages = [ inconsolata ];
|
||||
}
|
||||
];
|
||||
|
||||
script = ''
|
||||
exec foot "$@"
|
||||
'';
|
||||
}
|
||||
108
cmd/planterette/test/test.py
Normal file
108
cmd/planterette/test/test.py
Normal file
@@ -0,0 +1,108 @@
|
||||
import json
|
||||
import shlex
|
||||
|
||||
q = shlex.quote
|
||||
NODE_GROUPS = ["nodes", "floating_nodes"]
|
||||
|
||||
|
||||
def swaymsg(command: str = "", succeed=True, type="command"):
|
||||
assert command != "" or type != "command", "Must specify command or type"
|
||||
shell = q(f"swaymsg -t {q(type)} -- {q(command)}")
|
||||
with machine.nested(
|
||||
f"sending swaymsg {shell!r}" + " (allowed to fail)" * (not succeed)
|
||||
):
|
||||
ret = (machine.succeed if succeed else machine.execute)(
|
||||
f"su - alice -c {shell}"
|
||||
)
|
||||
|
||||
# execute also returns a status code, but disregard.
|
||||
if not succeed:
|
||||
_, ret = ret
|
||||
|
||||
if not succeed and not ret:
|
||||
return None
|
||||
|
||||
parsed = json.loads(ret)
|
||||
return parsed
|
||||
|
||||
|
||||
def walk(tree):
|
||||
yield tree
|
||||
for group in NODE_GROUPS:
|
||||
for node in tree.get(group, []):
|
||||
yield from walk(node)
|
||||
|
||||
|
||||
def wait_for_window(pattern):
|
||||
def func(last_chance):
|
||||
nodes = (node["name"] for node in walk(swaymsg(type="get_tree")))
|
||||
|
||||
if last_chance:
|
||||
nodes = list(nodes)
|
||||
machine.log(f"Last call! Current list of windows: {nodes}")
|
||||
|
||||
return any(pattern in name for name in nodes)
|
||||
|
||||
retry(func)
|
||||
|
||||
|
||||
def collect_state_ui(name):
|
||||
swaymsg(f"exec hakurei ps > '/tmp/{name}.ps'")
|
||||
machine.copy_from_vm(f"/tmp/{name}.ps", "")
|
||||
swaymsg(f"exec hakurei --json ps > '/tmp/{name}.json'")
|
||||
machine.copy_from_vm(f"/tmp/{name}.json", "")
|
||||
machine.screenshot(name)
|
||||
|
||||
|
||||
def check_state(name, enablements):
|
||||
instances = json.loads(machine.succeed("sudo -u alice -i XDG_RUNTIME_DIR=/run/user/1000 hakurei --json ps"))
|
||||
if len(instances) != 1:
|
||||
raise Exception(f"unexpected state length {len(instances)}")
|
||||
instance = next(iter(instances.values()))
|
||||
|
||||
config = instance['config']
|
||||
|
||||
if len(config['args']) != 1 or not (config['args'][0].startswith("/nix/store/")) or f"hakurei-{name}-" not in (config['args'][0]):
|
||||
raise Exception(f"unexpected args {instance['config']['args']}")
|
||||
|
||||
if config['enablements'] != enablements:
|
||||
raise Exception(f"unexpected enablements {instance['config']['enablements']}")
|
||||
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
|
||||
# To check hakurei's version:
|
||||
print(machine.succeed("sudo -u alice -i hakurei version"))
|
||||
|
||||
# Wait for Sway to complete startup:
|
||||
machine.wait_for_file("/run/user/1000/wayland-1")
|
||||
machine.wait_for_file("/tmp/sway-ipc.sock")
|
||||
|
||||
# Prepare planterette directory:
|
||||
machine.succeed("install -dm 0700 -o alice -g users /var/lib/hakurei/1000")
|
||||
|
||||
# Install planterette app:
|
||||
swaymsg("exec planterette -v install /etc/foot.pkg && touch /tmp/planterette-install-ok")
|
||||
machine.wait_for_file("/tmp/planterette-install-ok")
|
||||
|
||||
# Start app (foot) with Wayland enablement:
|
||||
swaymsg("exec planterette -v start org.codeberg.dnkl.foot")
|
||||
wait_for_window("hakurei@machine-foot")
|
||||
machine.send_chars("clear; wayland-info && touch /tmp/success-client\n")
|
||||
machine.wait_for_file("/tmp/hakurei.1000/tmpdir/2/success-client")
|
||||
collect_state_ui("app_wayland")
|
||||
check_state("foot", 13)
|
||||
# Verify acl on XDG_RUNTIME_DIR:
|
||||
print(machine.succeed("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 1000002"))
|
||||
machine.send_chars("exit\n")
|
||||
machine.wait_until_fails("pgrep foot")
|
||||
# Verify acl cleanup on XDG_RUNTIME_DIR:
|
||||
machine.wait_until_fails("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 1000002")
|
||||
|
||||
# Exit Sway and verify process exit status 0:
|
||||
swaymsg("exit", succeed=False)
|
||||
machine.wait_for_file("/tmp/sway-exit-ok")
|
||||
|
||||
# Print hakurei runDir contents:
|
||||
print(machine.succeed("find /run/user/1000/hakurei"))
|
||||
114
cmd/planterette/with.go
Normal file
114
cmd/planterette/with.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal"
|
||||
)
|
||||
|
||||
func withNixDaemon(
|
||||
ctx context.Context,
|
||||
action string, command []string, net bool, updateConfig func(config *hst.Config) *hst.Config,
|
||||
app *appInfo, pathSet *appPathSet, dropShell bool, beforeFail func(),
|
||||
) {
|
||||
mustRunAppDropShell(ctx, updateConfig(&hst.Config{
|
||||
ID: app.ID,
|
||||
|
||||
Path: shellPath,
|
||||
Args: []string{shellPath, "-lc", "rm -f /nix/var/nix/daemon-socket/socket && " +
|
||||
// start nix-daemon
|
||||
"nix-daemon --store / & " +
|
||||
// wait for socket to appear
|
||||
"(while [ ! -S /nix/var/nix/daemon-socket/socket ]; do sleep 0.01; done) && " +
|
||||
// create directory so nix stops complaining
|
||||
"mkdir -p /nix/var/nix/profiles/per-user/root/channels && " +
|
||||
strings.Join(command, " && ") +
|
||||
// terminate nix-daemon
|
||||
" && pkill nix-daemon",
|
||||
},
|
||||
|
||||
Username: "hakurei",
|
||||
Shell: shellPath,
|
||||
Data: pathSet.homeDir,
|
||||
Dir: path.Join("/data/data", app.ID),
|
||||
ExtraPerms: []*hst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
},
|
||||
|
||||
Identity: app.Identity,
|
||||
|
||||
Container: &hst.ContainerConfig{
|
||||
Hostname: formatHostname(app.Name) + "-" + action,
|
||||
Userns: true, // nix sandbox requires userns
|
||||
Net: net,
|
||||
SeccompFlags: seccomp.AllowMultiarch,
|
||||
Tty: dropShell,
|
||||
Filesystem: []*hst.FilesystemConfig{
|
||||
{Src: pathSet.nixPath, Dst: "/nix", Write: true, Must: true},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(pathSet.cacheDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
}), dropShell, beforeFail)
|
||||
}
|
||||
|
||||
func withCacheDir(
|
||||
ctx context.Context,
|
||||
action string, command []string, workDir string,
|
||||
app *appInfo, pathSet *appPathSet, dropShell bool, beforeFail func()) {
|
||||
mustRunAppDropShell(ctx, &hst.Config{
|
||||
ID: app.ID,
|
||||
|
||||
Path: shellPath,
|
||||
Args: []string{shellPath, "-lc", strings.Join(command, " && ")},
|
||||
|
||||
Username: "nixos",
|
||||
Shell: shellPath,
|
||||
Data: pathSet.cacheDir, // this also ensures cacheDir via shim
|
||||
Dir: path.Join("/data/data", app.ID, "cache"),
|
||||
ExtraPerms: []*hst.ExtraPermConfig{
|
||||
{Path: dataHome, Execute: true},
|
||||
{Ensure: true, Path: pathSet.baseDir, Read: true, Write: true, Execute: true},
|
||||
{Path: workDir, Execute: true},
|
||||
},
|
||||
|
||||
Identity: app.Identity,
|
||||
|
||||
Container: &hst.ContainerConfig{
|
||||
Hostname: formatHostname(app.Name) + "-" + action,
|
||||
SeccompFlags: seccomp.AllowMultiarch,
|
||||
Tty: dropShell,
|
||||
Filesystem: []*hst.FilesystemConfig{
|
||||
{Src: path.Join(workDir, "nix"), Dst: "/nix", Must: true},
|
||||
{Src: workDir, Dst: path.Join(hst.Tmp, "bundle"), Must: true},
|
||||
},
|
||||
Link: [][2]string{
|
||||
{app.CurrentSystem, "/run/current-system"},
|
||||
{"/run/current-system/sw/bin", "/bin"},
|
||||
{"/run/current-system/sw/bin", "/usr/bin"},
|
||||
},
|
||||
Etc: path.Join(workDir, "etc"),
|
||||
AutoEtc: true,
|
||||
},
|
||||
}, dropShell, beforeFail)
|
||||
}
|
||||
|
||||
func mustRunAppDropShell(ctx context.Context, config *hst.Config, dropShell bool, beforeFail func()) {
|
||||
if dropShell {
|
||||
config.Args = []string{shellPath, "-l"}
|
||||
mustRunApp(ctx, config, beforeFail)
|
||||
beforeFail()
|
||||
internal.Exit(0)
|
||||
}
|
||||
mustRunApp(ctx, config, beforeFail)
|
||||
}
|
||||
65
command/builder.go
Normal file
65
command/builder.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// New initialises a root Node.
|
||||
func New(output io.Writer, logf LogFunc, name string, early HandlerFunc) Command {
|
||||
c := rootNode{newNode(output, logf, name, "")}
|
||||
c.f = early
|
||||
return c
|
||||
}
|
||||
|
||||
func newNode(output io.Writer, logf LogFunc, name, usage string) *node {
|
||||
n := &node{
|
||||
name: name, usage: usage,
|
||||
out: output, logf: logf,
|
||||
set: flag.NewFlagSet(name, flag.ContinueOnError),
|
||||
}
|
||||
n.set.SetOutput(output)
|
||||
n.set.Usage = func() {
|
||||
_ = n.writeHelp()
|
||||
if n.suffix.Len() > 0 {
|
||||
_, _ = fmt.Fprintln(output, "Flags:")
|
||||
n.set.PrintDefaults()
|
||||
_, _ = fmt.Fprintln(output)
|
||||
}
|
||||
}
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
func (n *node) Command(name, usage string, f HandlerFunc) Node {
|
||||
n.NewCommand(name, usage, f)
|
||||
return n
|
||||
}
|
||||
|
||||
func (n *node) NewCommand(name, usage string, f HandlerFunc) Flag[Node] {
|
||||
if f == nil {
|
||||
panic("invalid handler")
|
||||
}
|
||||
if name == "" || usage == "" {
|
||||
panic("invalid subcommand")
|
||||
}
|
||||
|
||||
s := newNode(n.out, n.logf, name, usage)
|
||||
s.f = f
|
||||
if !n.adopt(s) {
|
||||
panic("attempted to initialise subcommand with non-unique name")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (n *node) New(name, usage string) Node {
|
||||
if name == "" || usage == "" {
|
||||
panic("invalid subcommand tree")
|
||||
}
|
||||
s := newNode(n.out, n.logf, name, usage)
|
||||
if !n.adopt(s) {
|
||||
panic("attempted to initialise subcommand tree with non-unique name")
|
||||
}
|
||||
return s
|
||||
}
|
||||
56
command/builder_test.go
Normal file
56
command/builder_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package command_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/command"
|
||||
)
|
||||
|
||||
func TestBuild(t *testing.T) {
|
||||
c := command.New(nil, nil, "test", nil)
|
||||
stubHandler := func([]string) error { panic("unreachable") }
|
||||
|
||||
t.Run("nil direct handler", func(t *testing.T) {
|
||||
defer checkRecover(t, "Command", "invalid handler")
|
||||
c.Command("name", "usage", nil)
|
||||
})
|
||||
|
||||
t.Run("direct zero length", func(t *testing.T) {
|
||||
wantPanic := "invalid subcommand"
|
||||
t.Run("zero length name", func(t *testing.T) { defer checkRecover(t, "Command", wantPanic); c.Command("", "usage", stubHandler) })
|
||||
t.Run("zero length usage", func(t *testing.T) { defer checkRecover(t, "Command", wantPanic); c.Command("name", "", stubHandler) })
|
||||
})
|
||||
|
||||
t.Run("direct adopt unique names", func(t *testing.T) {
|
||||
c.Command("d0", "usage", stubHandler)
|
||||
c.Command("d1", "usage", stubHandler)
|
||||
})
|
||||
|
||||
t.Run("direct adopt non-unique name", func(t *testing.T) {
|
||||
defer checkRecover(t, "Command", "attempted to initialise subcommand with non-unique name")
|
||||
c.Command("d0", "usage", stubHandler)
|
||||
})
|
||||
|
||||
t.Run("zero length", func(t *testing.T) {
|
||||
wantPanic := "invalid subcommand tree"
|
||||
t.Run("zero length name", func(t *testing.T) { defer checkRecover(t, "New", wantPanic); c.New("", "usage") })
|
||||
t.Run("zero length usage", func(t *testing.T) { defer checkRecover(t, "New", wantPanic); c.New("name", "") })
|
||||
})
|
||||
|
||||
t.Run("direct adopt unique names", func(t *testing.T) {
|
||||
c.New("t0", "usage")
|
||||
c.New("t1", "usage")
|
||||
})
|
||||
|
||||
t.Run("direct adopt non-unique name", func(t *testing.T) {
|
||||
defer checkRecover(t, "Command", "attempted to initialise subcommand tree with non-unique name")
|
||||
c.New("t0", "usage")
|
||||
})
|
||||
}
|
||||
|
||||
func checkRecover(t *testing.T, name, wantPanic string) {
|
||||
if r := recover(); r != wantPanic {
|
||||
t.Errorf("%s: panic = %v; wantPanic %v",
|
||||
name, r, wantPanic)
|
||||
}
|
||||
}
|
||||
55
command/command.go
Normal file
55
command/command.go
Normal file
@@ -0,0 +1,55 @@
|
||||
// Package command implements generic nested command parsing.
|
||||
package command
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// UsageInternal causes the command to be hidden from help text when set as the usage string.
|
||||
const UsageInternal = "internal"
|
||||
|
||||
type (
|
||||
// HandlerFunc is called when matching a directly handled subcommand tree.
|
||||
HandlerFunc = func(args []string) error
|
||||
|
||||
// LogFunc is the function signature of a printf function.
|
||||
LogFunc = func(format string, a ...any)
|
||||
|
||||
// FlagDefiner is a deferred flag definer value, usually encapsulating the default value.
|
||||
FlagDefiner interface {
|
||||
// Define defines the flag in set.
|
||||
Define(b *strings.Builder, set *flag.FlagSet, p any, name, usage string)
|
||||
}
|
||||
|
||||
Flag[T any] interface {
|
||||
// Flag defines a generic flag type in Node's flag set.
|
||||
Flag(p any, name string, value FlagDefiner, usage string) T
|
||||
}
|
||||
|
||||
Command interface {
|
||||
Parse(arguments []string) error
|
||||
|
||||
// MustParse determines exit outcomes for Parse errors
|
||||
// and calls handleError if [HandlerFunc] returns a non-nil error.
|
||||
MustParse(arguments []string, handleError func(error))
|
||||
|
||||
baseNode[Command]
|
||||
}
|
||||
Node baseNode[Node]
|
||||
|
||||
baseNode[T any] interface {
|
||||
// Command appends a subcommand with direct command handling.
|
||||
Command(name, usage string, f HandlerFunc) T
|
||||
|
||||
// New returns a new subcommand tree.
|
||||
New(name, usage string) (sub Node)
|
||||
// NewCommand returns a new subcommand with direct command handling.
|
||||
NewCommand(name, usage string, f HandlerFunc) (sub Flag[Node])
|
||||
|
||||
// PrintHelp prints a help message to the configured writer.
|
||||
PrintHelp()
|
||||
|
||||
Flag[T]
|
||||
}
|
||||
)
|
||||
77
command/flag.go
Normal file
77
command/flag.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FlagError wraps errors returned by [flag].
|
||||
type FlagError struct{ error }
|
||||
|
||||
func (e FlagError) Success() bool { return errors.Is(e.error, flag.ErrHelp) }
|
||||
func (e FlagError) Is(target error) bool {
|
||||
return (e.error == nil && target == nil) ||
|
||||
((e.error != nil && target != nil) && e.error.Error() == target.Error())
|
||||
}
|
||||
|
||||
func (n *node) Flag(p any, name string, value FlagDefiner, usage string) Node {
|
||||
value.Define(&n.suffix, n.set, p, name, usage)
|
||||
return n
|
||||
}
|
||||
|
||||
// StringFlag is the default value of a string flag.
|
||||
type StringFlag string
|
||||
|
||||
func (v StringFlag) Define(b *strings.Builder, set *flag.FlagSet, p any, name, usage string) {
|
||||
set.StringVar(p.(*string), name, string(v), usage)
|
||||
b.WriteString(" [" + prettyFlag(name) + " <value>]")
|
||||
}
|
||||
|
||||
// IntFlag is the default value of an int flag.
|
||||
type IntFlag int
|
||||
|
||||
func (v IntFlag) Define(b *strings.Builder, set *flag.FlagSet, p any, name, usage string) {
|
||||
set.IntVar(p.(*int), name, int(v), usage)
|
||||
b.WriteString(" [" + prettyFlag(name) + " <int>]")
|
||||
}
|
||||
|
||||
// BoolFlag is the default value of a bool flag.
|
||||
type BoolFlag bool
|
||||
|
||||
func (v BoolFlag) Define(b *strings.Builder, set *flag.FlagSet, p any, name, usage string) {
|
||||
set.BoolVar(p.(*bool), name, bool(v), usage)
|
||||
b.WriteString(" [" + prettyFlag(name) + "]")
|
||||
}
|
||||
|
||||
// RepeatableFlag implements an ordered, repeatable string flag.
|
||||
type RepeatableFlag []string
|
||||
|
||||
func (r *RepeatableFlag) String() string {
|
||||
if r == nil {
|
||||
return "<nil>"
|
||||
}
|
||||
return strings.Join(*r, " ")
|
||||
}
|
||||
|
||||
func (r *RepeatableFlag) Set(v string) error {
|
||||
*r = append(*r, v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RepeatableFlag) Define(b *strings.Builder, set *flag.FlagSet, _ any, name, usage string) {
|
||||
set.Var(r, name, usage)
|
||||
b.WriteString(" [" + prettyFlag(name) + " <value>]")
|
||||
}
|
||||
|
||||
// this has no effect on parse outcome
|
||||
func prettyFlag(name string) string {
|
||||
switch len(name) {
|
||||
case 0:
|
||||
panic("zero length flag name")
|
||||
case 1:
|
||||
return "-" + name
|
||||
default:
|
||||
return "--" + name
|
||||
}
|
||||
}
|
||||
53
command/help.go
Normal file
53
command/help.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
)
|
||||
|
||||
var ErrHelp = errors.New("help requested")
|
||||
|
||||
func (n *node) PrintHelp() { _ = n.writeHelp() }
|
||||
|
||||
func (n *node) writeHelp() error {
|
||||
if _, err := fmt.Fprintf(n.out,
|
||||
"\nUsage:\t%s [-h | --help]%s COMMAND [OPTIONS]\n",
|
||||
strings.Join(append(n.prefix, n.name), " "), &n.suffix,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if n.child != nil {
|
||||
if _, err := fmt.Fprint(n.out, "\nCommands:\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
tw := tabwriter.NewWriter(n.out, 0, 1, 4, ' ', 0)
|
||||
if err := n.child.writeCommands(tw); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := n.out.Write([]byte{'\n'})
|
||||
if err == nil {
|
||||
err = ErrHelp
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (n *node) writeCommands(w io.Writer) error {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
if n.usage != UsageInternal {
|
||||
if _, err := fmt.Fprintf(w, "\t%s\t%s\n", n.name, n.usage); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return n.next.writeCommands(w)
|
||||
}
|
||||
40
command/node.go
Normal file
40
command/node.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type node struct {
|
||||
child, next *node
|
||||
name, usage string
|
||||
|
||||
out io.Writer
|
||||
logf LogFunc
|
||||
|
||||
prefix []string
|
||||
suffix strings.Builder
|
||||
|
||||
f HandlerFunc
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
func (n *node) adopt(v *node) bool {
|
||||
if n.child != nil {
|
||||
return n.child.append(v)
|
||||
}
|
||||
n.child = v
|
||||
return true
|
||||
}
|
||||
|
||||
func (n *node) append(v *node) bool {
|
||||
if n.name == v.name {
|
||||
return false
|
||||
}
|
||||
if n.next != nil {
|
||||
return n.next.append(v)
|
||||
}
|
||||
n.next = v
|
||||
return true
|
||||
}
|
||||
105
command/parse.go
Normal file
105
command/parse.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEmptyTree = errors.New("subcommand tree has no nodes")
|
||||
ErrNoMatch = errors.New("did not match any subcommand")
|
||||
)
|
||||
|
||||
func (n *node) Parse(arguments []string) error {
|
||||
if n.usage == "" { // root node has zero length usage
|
||||
if n.next != nil {
|
||||
panic("invalid toplevel state")
|
||||
}
|
||||
goto match
|
||||
}
|
||||
|
||||
if len(arguments) == 0 {
|
||||
// unreachable: zero length args cause upper level to return with a help message
|
||||
panic("attempted to parse with zero length args")
|
||||
}
|
||||
if arguments[0] != n.name {
|
||||
if n.next == nil {
|
||||
n.printf("%q is not a valid command", arguments[0])
|
||||
return ErrNoMatch
|
||||
}
|
||||
n.next.prefix = n.prefix
|
||||
return n.next.Parse(arguments)
|
||||
}
|
||||
arguments = arguments[1:]
|
||||
|
||||
match:
|
||||
if n.child != nil {
|
||||
// propagate help prefix early: flag set usage dereferences help
|
||||
n.child.prefix = append(n.prefix, n.name)
|
||||
}
|
||||
|
||||
if n.set.Parsed() {
|
||||
panic("invalid set state")
|
||||
}
|
||||
if err := n.set.Parse(arguments); err != nil {
|
||||
return FlagError{err}
|
||||
}
|
||||
args := n.set.Args()
|
||||
|
||||
if n.child != nil {
|
||||
if n.f != nil {
|
||||
if n.usage != "" { // root node early special case
|
||||
panic("invalid subcommand tree state")
|
||||
}
|
||||
|
||||
// special case: root node calls HandlerFunc for initialisation
|
||||
if err := n.f(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(args) == 0 {
|
||||
return n.writeHelp()
|
||||
}
|
||||
return n.child.Parse(args)
|
||||
}
|
||||
|
||||
if n.f == nil {
|
||||
n.printf("%q has no subcommands", n.name)
|
||||
return ErrEmptyTree
|
||||
}
|
||||
return n.f(args)
|
||||
}
|
||||
|
||||
func (n *node) printf(format string, a ...any) {
|
||||
if n.logf == nil {
|
||||
log.Printf(format, a...)
|
||||
} else {
|
||||
n.logf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *node) MustParse(arguments []string, handleError func(error)) {
|
||||
switch err := n.Parse(arguments); err {
|
||||
case nil:
|
||||
return
|
||||
case ErrHelp:
|
||||
os.Exit(0)
|
||||
case ErrNoMatch:
|
||||
os.Exit(1)
|
||||
case ErrEmptyTree:
|
||||
os.Exit(1)
|
||||
default:
|
||||
var flagError FlagError
|
||||
if !errors.As(err, &flagError) { // returned by HandlerFunc
|
||||
handleError(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if flagError.Success() {
|
||||
os.Exit(0)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
344
command/parse_test.go
Normal file
344
command/parse_test.go
Normal file
@@ -0,0 +1,344 @@
|
||||
package command_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/command"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
buildTree func(wout, wlog io.Writer) command.Command
|
||||
args []string
|
||||
want string
|
||||
wantLog string
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
"d=0 empty sub",
|
||||
func(wout, wlog io.Writer) command.Command { return command.New(wout, newLogFunc(wlog), "root", nil) },
|
||||
[]string{""},
|
||||
"", "test: \"root\" has no subcommands\n", command.ErrEmptyTree,
|
||||
},
|
||||
{
|
||||
"d=0 empty sub garbage",
|
||||
func(wout, wlog io.Writer) command.Command { return command.New(wout, newLogFunc(wlog), "root", nil) },
|
||||
[]string{"a", "b", "c", "d"},
|
||||
"", "test: \"root\" has no subcommands\n", command.ErrEmptyTree,
|
||||
},
|
||||
{
|
||||
"d=0 no match",
|
||||
buildTestCommand,
|
||||
[]string{"nonexistent"},
|
||||
"", "test: \"nonexistent\" is not a valid command\n", command.ErrNoMatch,
|
||||
},
|
||||
{
|
||||
"d=0 direct error",
|
||||
buildTestCommand,
|
||||
[]string{"error"},
|
||||
"", "", errSuccess,
|
||||
},
|
||||
{
|
||||
"d=0 direct error garbage",
|
||||
buildTestCommand,
|
||||
[]string{"error", "0", "1", "2"},
|
||||
"", "", errSuccess,
|
||||
},
|
||||
{
|
||||
"d=0 direct success out of order",
|
||||
buildTestCommand,
|
||||
[]string{"succeed"},
|
||||
"", "", nil,
|
||||
},
|
||||
{
|
||||
"d=0 direct success output",
|
||||
buildTestCommand,
|
||||
[]string{"print", "0", "1", "2"},
|
||||
"012", "", nil,
|
||||
},
|
||||
{
|
||||
"d=0 out of order string flag",
|
||||
buildTestCommand,
|
||||
[]string{"string", "--string", "64d3b4b7b21788585845060e2199a78f"},
|
||||
"flag provided but not defined: -string\n\nUsage:\ttest string [-h | --help] COMMAND [OPTIONS]\n\n", "",
|
||||
errors.New("flag provided but not defined: -string"),
|
||||
},
|
||||
{
|
||||
"d=0 string flag",
|
||||
buildTestCommand,
|
||||
[]string{"--string", "64d3b4b7b21788585845060e2199a78f", "string"},
|
||||
"64d3b4b7b21788585845060e2199a78f", "", nil,
|
||||
},
|
||||
{
|
||||
"d=0 int flag",
|
||||
buildTestCommand,
|
||||
[]string{"--int", "2147483647", "int"},
|
||||
"2147483647", "", nil,
|
||||
},
|
||||
{
|
||||
"d=0 repeat flag",
|
||||
buildTestCommand,
|
||||
[]string{"--repeat", "0", "--repeat", "1", "--repeat", "2", "--repeat", "3", "--repeat", "4", "repeat"},
|
||||
"[0 1 2 3 4]", "", nil,
|
||||
},
|
||||
{
|
||||
"d=0 bool flag",
|
||||
buildTestCommand,
|
||||
[]string{"-v", "succeed"},
|
||||
"", "test: verbose\n", nil,
|
||||
},
|
||||
{
|
||||
"d=0 bool flag early error",
|
||||
buildTestCommand,
|
||||
[]string{"--fail", "succeed"},
|
||||
"", "", errSuccess,
|
||||
},
|
||||
|
||||
{
|
||||
"d=1 empty sub",
|
||||
buildTestCommand,
|
||||
[]string{"empty"},
|
||||
"", "test: \"empty\" has no subcommands\n", command.ErrEmptyTree,
|
||||
},
|
||||
{
|
||||
"d=1 empty sub garbage",
|
||||
buildTestCommand,
|
||||
[]string{"empty", "a", "b", "c", "d"},
|
||||
"", "test: \"empty\" has no subcommands\n", command.ErrEmptyTree,
|
||||
},
|
||||
{
|
||||
"d=1 empty sub help",
|
||||
buildTestCommand,
|
||||
[]string{"empty", "-h"},
|
||||
"\nUsage:\ttest empty [-h | --help] COMMAND [OPTIONS]\n\n", "", flag.ErrHelp,
|
||||
},
|
||||
{
|
||||
"d=1 no match",
|
||||
buildTestCommand,
|
||||
[]string{"join", "23aa3bb0", "34986782", "d8859355", "cd9ac317", ", "},
|
||||
"", "test: \"23aa3bb0\" is not a valid command\n", command.ErrNoMatch,
|
||||
},
|
||||
{
|
||||
"d=1 direct success out",
|
||||
buildTestCommand,
|
||||
[]string{"join", "out", "23aa3bb0", "34986782", "d8859355", "cd9ac317", ", "},
|
||||
"23aa3bb0, 34986782, d8859355, cd9ac317", "", nil,
|
||||
},
|
||||
{
|
||||
"d=1 direct success log",
|
||||
buildTestCommand,
|
||||
[]string{"join", "log", "23aa3bb0", "34986782", "d8859355", "cd9ac317", ", "},
|
||||
"", "test: 23aa3bb0, 34986782, d8859355, cd9ac317\n", nil,
|
||||
},
|
||||
|
||||
{
|
||||
"d=4 empty sub",
|
||||
buildTestCommand,
|
||||
[]string{"deep", "d=2", "d=3", "d=4"},
|
||||
"", "test: \"d=4\" has no subcommands\n", command.ErrEmptyTree},
|
||||
|
||||
{
|
||||
"d=0 help",
|
||||
buildTestCommand,
|
||||
[]string{},
|
||||
`
|
||||
Usage: test [-h | --help] [-v] [--fail] [--string <value>] [--int <int>] [--repeat <value>] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
error return an error
|
||||
print wraps Fprint
|
||||
string print string passed by flag
|
||||
int print int passed by flag
|
||||
repeat print repeated values passed by flag
|
||||
empty empty subcommand
|
||||
join wraps strings.Join
|
||||
succeed this command succeeds
|
||||
deep top level of command tree with various levels
|
||||
|
||||
`, "", command.ErrHelp,
|
||||
},
|
||||
{
|
||||
"d=0 help flag",
|
||||
buildTestCommand,
|
||||
[]string{"-h"},
|
||||
`
|
||||
Usage: test [-h | --help] [-v] [--fail] [--string <value>] [--int <int>] [--repeat <value>] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
error return an error
|
||||
print wraps Fprint
|
||||
string print string passed by flag
|
||||
int print int passed by flag
|
||||
repeat print repeated values passed by flag
|
||||
empty empty subcommand
|
||||
join wraps strings.Join
|
||||
succeed this command succeeds
|
||||
deep top level of command tree with various levels
|
||||
|
||||
Flags:
|
||||
-fail
|
||||
fail early
|
||||
-int int
|
||||
store value for the "int" command (default -1)
|
||||
-repeat value
|
||||
store value for the "repeat" command
|
||||
-string string
|
||||
store value for the "string" command (default "default")
|
||||
-v verbose output
|
||||
|
||||
`, "", flag.ErrHelp,
|
||||
},
|
||||
|
||||
{
|
||||
"d=1 help",
|
||||
buildTestCommand,
|
||||
[]string{"join"},
|
||||
`
|
||||
Usage: test join [-h | --help] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
out write result to wout
|
||||
log log result to wlog
|
||||
|
||||
`, "", command.ErrHelp,
|
||||
},
|
||||
{
|
||||
"d=1 help flag",
|
||||
buildTestCommand,
|
||||
[]string{"join", "-h"},
|
||||
`
|
||||
Usage: test join [-h | --help] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
out write result to wout
|
||||
log log result to wlog
|
||||
|
||||
`, "", flag.ErrHelp,
|
||||
},
|
||||
|
||||
{
|
||||
"d=2 help",
|
||||
buildTestCommand,
|
||||
[]string{"deep", "d=2"},
|
||||
`
|
||||
Usage: test deep d=2 [-h | --help] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
d=3 relative third level
|
||||
|
||||
`, "", command.ErrHelp,
|
||||
},
|
||||
{
|
||||
"d=2 help flag",
|
||||
buildTestCommand,
|
||||
[]string{"deep", "d=2", "-h"},
|
||||
`
|
||||
Usage: test deep d=2 [-h | --help] COMMAND [OPTIONS]
|
||||
|
||||
Commands:
|
||||
d=3 relative third level
|
||||
|
||||
`, "", flag.ErrHelp,
|
||||
},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
wout, wlog := new(bytes.Buffer), new(bytes.Buffer)
|
||||
c := tc.buildTree(wout, wlog)
|
||||
|
||||
if err := c.Parse(tc.args); !errors.Is(err, tc.wantErr) {
|
||||
t.Errorf("Parse: error = %v; wantErr %v", err, tc.wantErr)
|
||||
}
|
||||
if got := wout.String(); got != tc.want {
|
||||
t.Errorf("Parse: %s want %s", got, tc.want)
|
||||
}
|
||||
if gotLog := wlog.String(); gotLog != tc.wantLog {
|
||||
t.Errorf("Parse: log = %s wantLog %s", gotLog, tc.wantLog)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
errJoinLen = errors.New("not enough arguments to join")
|
||||
errSuccess = errors.New("success")
|
||||
)
|
||||
|
||||
func buildTestCommand(wout, wlog io.Writer) (c command.Command) {
|
||||
var (
|
||||
flagVerbose bool
|
||||
flagFail bool
|
||||
|
||||
flagString string
|
||||
flagInt int
|
||||
flagRepeat command.RepeatableFlag
|
||||
)
|
||||
|
||||
logf := newLogFunc(wlog)
|
||||
c = command.New(wout, logf, "test", func([]string) error {
|
||||
if flagVerbose {
|
||||
logf("verbose")
|
||||
}
|
||||
if flagFail {
|
||||
return errSuccess
|
||||
}
|
||||
return nil
|
||||
}).
|
||||
Flag(&flagVerbose, "v", command.BoolFlag(false), "verbose output").
|
||||
Flag(&flagFail, "fail", command.BoolFlag(false), "fail early").
|
||||
Command("error", "return an error", func([]string) error {
|
||||
return errSuccess
|
||||
}).
|
||||
Command("print", "wraps Fprint", func(args []string) error {
|
||||
a := make([]any, len(args))
|
||||
for i, v := range args {
|
||||
a[i] = v
|
||||
}
|
||||
_, err := fmt.Fprint(wout, a...)
|
||||
return err
|
||||
}).
|
||||
Flag(&flagString, "string", command.StringFlag("default"), "store value for the \"string\" command").
|
||||
Command("string", "print string passed by flag", func(args []string) error { _, err := fmt.Fprint(wout, flagString); return err }).
|
||||
Flag(&flagInt, "int", command.IntFlag(-1), "store value for the \"int\" command").
|
||||
Command("int", "print int passed by flag", func(args []string) error { _, err := fmt.Fprint(wout, flagInt); return err }).
|
||||
Flag(nil, "repeat", &flagRepeat, "store value for the \"repeat\" command").
|
||||
Command("repeat", "print repeated values passed by flag", func(args []string) error { _, err := fmt.Fprint(wout, flagRepeat); return err })
|
||||
|
||||
c.New("empty", "empty subcommand")
|
||||
c.New("hidden", command.UsageInternal)
|
||||
|
||||
c.New("join", "wraps strings.Join").
|
||||
Command("out", "write result to wout", func(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errJoinLen
|
||||
}
|
||||
_, err := fmt.Fprint(wout, strings.Join(args[:len(args)-1], args[len(args)-1]))
|
||||
return err
|
||||
}).
|
||||
Command("log", "log result to wlog", func(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errJoinLen
|
||||
}
|
||||
logf("%s", strings.Join(args[:len(args)-1], args[len(args)-1]))
|
||||
return nil
|
||||
})
|
||||
|
||||
c.Command("succeed", "this command succeeds", func([]string) error { return nil })
|
||||
|
||||
c.New("deep", "top level of command tree with various levels").
|
||||
New("d=2", "relative second level").
|
||||
New("d=3", "relative third level").
|
||||
New("d=4", "relative fourth level")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func newLogFunc(w io.Writer) command.LogFunc { return log.New(w, "test: ", 0).Printf }
|
||||
54
command/unreachable_test.go
Normal file
54
command/unreachable_test.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseUnreachable(t *testing.T) {
|
||||
// top level bypasses name matching and recursive calls to Parse
|
||||
// returns when encountering zero-length args
|
||||
t.Run("zero-length args", func(t *testing.T) {
|
||||
defer checkRecover(t, "Parse", "attempted to parse with zero length args")
|
||||
_ = newNode(panicWriter{}, nil, " ", " ").Parse(nil)
|
||||
})
|
||||
|
||||
// top level must not have siblings
|
||||
t.Run("toplevel siblings", func(t *testing.T) {
|
||||
defer checkRecover(t, "Parse", "invalid toplevel state")
|
||||
n := newNode(panicWriter{}, nil, " ", "")
|
||||
n.append(newNode(panicWriter{}, nil, " ", " "))
|
||||
_ = n.Parse(nil)
|
||||
})
|
||||
|
||||
// a node with descendents must not have a direct handler
|
||||
t.Run("sub handle conflict", func(t *testing.T) {
|
||||
defer checkRecover(t, "Parse", "invalid subcommand tree state")
|
||||
n := newNode(panicWriter{}, nil, " ", " ")
|
||||
n.adopt(newNode(panicWriter{}, nil, " ", " "))
|
||||
n.f = func([]string) error { panic("unreachable") }
|
||||
_ = n.Parse([]string{" "})
|
||||
})
|
||||
|
||||
// this would only happen if a node was matched twice
|
||||
t.Run("parsed flag set", func(t *testing.T) {
|
||||
defer checkRecover(t, "Parse", "invalid set state")
|
||||
n := newNode(panicWriter{}, nil, " ", "")
|
||||
set := flag.NewFlagSet("parsed", flag.ContinueOnError)
|
||||
set.SetOutput(panicWriter{})
|
||||
_ = set.Parse(nil)
|
||||
n.set = set
|
||||
_ = n.Parse(nil)
|
||||
})
|
||||
}
|
||||
|
||||
type panicWriter struct{}
|
||||
|
||||
func (p panicWriter) Write([]byte) (int, error) { panic("unreachable") }
|
||||
|
||||
func checkRecover(t *testing.T, name, wantPanic string) {
|
||||
if r := recover(); r != wantPanic {
|
||||
t.Errorf("%s: panic = %v; wantPanic %v",
|
||||
name, r, wantPanic)
|
||||
}
|
||||
}
|
||||
14
command/wrap.go
Normal file
14
command/wrap.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package command
|
||||
|
||||
// the top level node wants [Command] returned for its builder methods
|
||||
type rootNode struct{ *node }
|
||||
|
||||
func (r rootNode) Command(name, usage string, f HandlerFunc) Command {
|
||||
r.node.Command(name, usage, f)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r rootNode) Flag(p any, name string, value FlagDefiner, usage string) Command {
|
||||
r.node.Flag(p, name, value, usage)
|
||||
return r
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
#compdef fortify
|
||||
|
||||
_fortify_app() {
|
||||
__fortify_files
|
||||
return $?
|
||||
}
|
||||
|
||||
_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]'
|
||||
}
|
||||
|
||||
_fortify_ps() {
|
||||
_arguments \
|
||||
'--short[Print instance id]'
|
||||
}
|
||||
|
||||
_fortify_show() {
|
||||
_alternative \
|
||||
'instances:domains:__fortify_instances' \
|
||||
'files:files:__fortify_files'
|
||||
}
|
||||
|
||||
__fortify_files() {
|
||||
_files -g "*.(json|ftfy)"
|
||||
return $?
|
||||
}
|
||||
|
||||
__fortify_instances() {
|
||||
local -a out
|
||||
shift -p
|
||||
out=( ${(f)"$(_call_program commands fortify ps --short 2>&1)"} )
|
||||
if (( $#out == 0 )); then
|
||||
_message "No active instances"
|
||||
else
|
||||
_describe "active instances" out
|
||||
fi
|
||||
return $?
|
||||
}
|
||||
|
||||
(( $+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"
|
||||
"show:Show the contents of an app configuration"
|
||||
"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 'action' _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]' \
|
||||
'--json[Format output in JSON when applicable]' \
|
||||
'*::fortify command:_fortify_commands'
|
||||
45
container/capability.go
Normal file
45
container/capability.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
_LINUX_CAPABILITY_VERSION_3 = 0x20080522
|
||||
|
||||
PR_CAP_AMBIENT = 0x2f
|
||||
PR_CAP_AMBIENT_RAISE = 0x2
|
||||
PR_CAP_AMBIENT_CLEAR_ALL = 0x4
|
||||
|
||||
CAP_SYS_ADMIN = 0x15
|
||||
CAP_SETPCAP = 0x8
|
||||
)
|
||||
|
||||
type (
|
||||
capHeader struct {
|
||||
version uint32
|
||||
pid int32
|
||||
}
|
||||
|
||||
capData struct {
|
||||
effective uint32
|
||||
permitted uint32
|
||||
inheritable uint32
|
||||
}
|
||||
)
|
||||
|
||||
// See CAP_TO_INDEX in linux/capability.h:
|
||||
func capToIndex(cap uintptr) uintptr { return cap >> 5 }
|
||||
|
||||
// See CAP_TO_MASK in linux/capability.h:
|
||||
func capToMask(cap uintptr) uint32 { return 1 << uint(cap&31) }
|
||||
|
||||
func capset(hdrp *capHeader, datap *[2]capData) error {
|
||||
if _, _, errno := syscall.Syscall(syscall.SYS_CAPSET,
|
||||
uintptr(unsafe.Pointer(hdrp)),
|
||||
uintptr(unsafe.Pointer(&datap[0])), 0); errno != 0 {
|
||||
return errno
|
||||
}
|
||||
return nil
|
||||
}
|
||||
257
container/container.go
Normal file
257
container/container.go
Normal file
@@ -0,0 +1,257 @@
|
||||
// Package container implements unprivileged Linux containers with built-in support for syscall filtering.
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"strconv"
|
||||
. "syscall"
|
||||
"time"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
)
|
||||
|
||||
const (
|
||||
// Nonexistent is a path that cannot exist.
|
||||
// /proc is chosen because a system with covered /proc is unsupported by this package.
|
||||
Nonexistent = "/proc/nonexistent"
|
||||
|
||||
// CancelSignal is the signal expected by container init on context cancel.
|
||||
// A custom [Container.Cancel] function must eventually deliver this signal.
|
||||
CancelSignal = SIGTERM
|
||||
)
|
||||
|
||||
type (
|
||||
// Container represents a container environment being prepared or run.
|
||||
// None of [Container] methods are safe for concurrent use.
|
||||
Container struct {
|
||||
// Name of initial process in the container.
|
||||
name string
|
||||
// Cgroup fd, nil to disable.
|
||||
Cgroup *int
|
||||
// ExtraFiles passed through to initial process in the container,
|
||||
// with behaviour identical to its [exec.Cmd] counterpart.
|
||||
ExtraFiles []*os.File
|
||||
|
||||
// param encoder for shim and init
|
||||
setup *gob.Encoder
|
||||
// cancels cmd
|
||||
cancel context.CancelFunc
|
||||
|
||||
Stdin io.Reader
|
||||
Stdout io.Writer
|
||||
Stderr io.Writer
|
||||
|
||||
Cancel func(cmd *exec.Cmd) error
|
||||
WaitDelay time.Duration
|
||||
|
||||
cmd *exec.Cmd
|
||||
ctx context.Context
|
||||
Params
|
||||
}
|
||||
|
||||
// Params holds container configuration and is safe to serialise.
|
||||
Params struct {
|
||||
// Working directory in the container.
|
||||
Dir string
|
||||
// Initial process environment.
|
||||
Env []string
|
||||
// Absolute path of initial process in the container. Overrides name.
|
||||
Path string
|
||||
// Initial process argv.
|
||||
Args []string
|
||||
// Deliver SIGINT to the initial process on context cancellation.
|
||||
ForwardCancel bool
|
||||
// time to wait for linger processes after death of initial process
|
||||
AdoptWaitDelay time.Duration
|
||||
|
||||
// Mapped Uid in user namespace.
|
||||
Uid int
|
||||
// Mapped Gid in user namespace.
|
||||
Gid int
|
||||
// Hostname value in UTS namespace.
|
||||
Hostname string
|
||||
// Sequential container setup ops.
|
||||
*Ops
|
||||
|
||||
// Seccomp system call filter rules.
|
||||
SeccompRules []seccomp.NativeRule
|
||||
// Extra seccomp flags.
|
||||
SeccompFlags seccomp.ExportFlag
|
||||
// Seccomp presets. Has no effect unless SeccompRules is zero-length.
|
||||
SeccompPresets seccomp.FilterPreset
|
||||
// Do not load seccomp program.
|
||||
SeccompDisable bool
|
||||
|
||||
// Permission bits of newly created parent directories.
|
||||
// The zero value is interpreted as 0755.
|
||||
ParentPerm os.FileMode
|
||||
// Do not syscall.Setsid.
|
||||
RetainSession bool
|
||||
// Do not [syscall.CLONE_NEWNET].
|
||||
HostNet bool
|
||||
// Retain CAP_SYS_ADMIN.
|
||||
Privileged bool
|
||||
}
|
||||
)
|
||||
|
||||
// Start starts the container init. The init process blocks until Serve is called.
|
||||
func (p *Container) Start() error {
|
||||
if p.cmd != nil {
|
||||
return errors.New("container: already started")
|
||||
}
|
||||
if p.Ops == nil || len(*p.Ops) == 0 {
|
||||
return errors.New("container: starting an empty container")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(p.ctx)
|
||||
p.cancel = cancel
|
||||
|
||||
var cloneFlags uintptr = CLONE_NEWIPC | CLONE_NEWUTS | CLONE_NEWCGROUP
|
||||
if !p.HostNet {
|
||||
cloneFlags |= CLONE_NEWNET
|
||||
}
|
||||
|
||||
// map to overflow id to work around ownership checks
|
||||
if p.Uid < 1 {
|
||||
p.Uid = OverflowUid()
|
||||
}
|
||||
if p.Gid < 1 {
|
||||
p.Gid = OverflowGid()
|
||||
}
|
||||
|
||||
if !p.RetainSession {
|
||||
p.SeccompPresets |= seccomp.PresetDenyTTY
|
||||
}
|
||||
|
||||
if p.AdoptWaitDelay == 0 {
|
||||
p.AdoptWaitDelay = 5 * time.Second
|
||||
}
|
||||
// to allow disabling this behaviour
|
||||
if p.AdoptWaitDelay < 0 {
|
||||
p.AdoptWaitDelay = 0
|
||||
}
|
||||
|
||||
p.cmd = exec.CommandContext(ctx, MustExecutable())
|
||||
p.cmd.Args = []string{initName}
|
||||
p.cmd.Stdin, p.cmd.Stdout, p.cmd.Stderr = p.Stdin, p.Stdout, p.Stderr
|
||||
p.cmd.WaitDelay = p.WaitDelay
|
||||
if p.Cancel != nil {
|
||||
p.cmd.Cancel = func() error { return p.Cancel(p.cmd) }
|
||||
} else {
|
||||
p.cmd.Cancel = func() error { return p.cmd.Process.Signal(CancelSignal) }
|
||||
}
|
||||
p.cmd.Dir = "/"
|
||||
p.cmd.SysProcAttr = &SysProcAttr{
|
||||
Setsid: !p.RetainSession,
|
||||
Pdeathsig: SIGKILL,
|
||||
Cloneflags: cloneFlags | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS,
|
||||
|
||||
// remain privileged for setup
|
||||
AmbientCaps: []uintptr{CAP_SYS_ADMIN, CAP_SETPCAP},
|
||||
|
||||
UseCgroupFD: p.Cgroup != nil,
|
||||
}
|
||||
if p.cmd.SysProcAttr.UseCgroupFD {
|
||||
p.cmd.SysProcAttr.CgroupFD = *p.Cgroup
|
||||
}
|
||||
|
||||
// place setup pipe before user supplied extra files, this is later restored by init
|
||||
if fd, e, err := Setup(&p.cmd.ExtraFiles); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
"cannot create shim setup pipe:")
|
||||
} else {
|
||||
p.setup = e
|
||||
p.cmd.Env = []string{setupEnv + "=" + strconv.Itoa(fd)}
|
||||
}
|
||||
p.cmd.ExtraFiles = append(p.cmd.ExtraFiles, p.ExtraFiles...)
|
||||
|
||||
msg.Verbose("starting container init")
|
||||
if err := p.cmd.Start(); err != nil {
|
||||
return msg.WrapErr(err, err.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Serve serves [Container.Params] to the container init.
|
||||
// Serve must only be called once.
|
||||
func (p *Container) Serve() error {
|
||||
if p.setup == nil {
|
||||
panic("invalid serve")
|
||||
}
|
||||
|
||||
setup := p.setup
|
||||
p.setup = nil
|
||||
|
||||
if p.Path != "" && !path.IsAbs(p.Path) {
|
||||
p.cancel()
|
||||
return msg.WrapErr(EINVAL,
|
||||
fmt.Sprintf("invalid executable path %q", p.Path))
|
||||
}
|
||||
|
||||
if p.Path == "" {
|
||||
if p.name == "" {
|
||||
p.Path = os.Getenv("SHELL")
|
||||
if !path.IsAbs(p.Path) {
|
||||
p.cancel()
|
||||
return msg.WrapErr(EBADE,
|
||||
"no command specified and $SHELL is invalid")
|
||||
}
|
||||
p.name = path.Base(p.Path)
|
||||
} else if path.IsAbs(p.name) {
|
||||
p.Path = p.name
|
||||
} else if v, err := exec.LookPath(p.name); err != nil {
|
||||
p.cancel()
|
||||
return msg.WrapErr(err, err.Error())
|
||||
} else {
|
||||
p.Path = v
|
||||
}
|
||||
}
|
||||
|
||||
if p.SeccompRules == nil {
|
||||
// do not transmit nil
|
||||
p.SeccompRules = make([]seccomp.NativeRule, 0)
|
||||
}
|
||||
|
||||
err := setup.Encode(
|
||||
&initParams{
|
||||
p.Params,
|
||||
Getuid(),
|
||||
Getgid(),
|
||||
len(p.ExtraFiles),
|
||||
msg.IsVerbose(),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
p.cancel()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Wait waits for the container init process to exit.
|
||||
func (p *Container) Wait() error { defer p.cancel(); return p.cmd.Wait() }
|
||||
|
||||
func (p *Container) String() string {
|
||||
return fmt.Sprintf("argv: %q, filter: %v, rules: %d, flags: %#x, presets: %#x",
|
||||
p.Args, !p.SeccompDisable, len(p.SeccompRules), int(p.SeccompFlags), int(p.SeccompPresets))
|
||||
}
|
||||
|
||||
// ProcessState returns the address to os.ProcessState held by the underlying [exec.Cmd].
|
||||
func (p *Container) ProcessState() *os.ProcessState {
|
||||
if p.cmd == nil {
|
||||
return nil
|
||||
}
|
||||
return p.cmd.ProcessState
|
||||
}
|
||||
|
||||
func New(ctx context.Context, name string, args ...string) *Container {
|
||||
return &Container{name: name, ctx: ctx,
|
||||
Params: Params{Args: append([]string{name}, args...), Dir: "/", Ops: new(Ops)},
|
||||
}
|
||||
}
|
||||
368
container/container_test.go
Normal file
368
container/container_test.go
Normal file
@@ -0,0 +1,368 @@
|
||||
package container_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/command"
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/container/seccomp"
|
||||
"hakurei.app/container/vfs"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/hlog"
|
||||
)
|
||||
|
||||
const (
|
||||
ignore = "\x00"
|
||||
ignoreV = -1
|
||||
|
||||
pathWantMnt = "/etc/hakurei/want-mnt"
|
||||
)
|
||||
|
||||
var containerTestCases = []struct {
|
||||
name string
|
||||
filter bool
|
||||
session bool
|
||||
net bool
|
||||
ops *container.Ops
|
||||
|
||||
mnt []*vfs.MountInfoEntry
|
||||
uid int
|
||||
gid int
|
||||
|
||||
rules []seccomp.NativeRule
|
||||
flags seccomp.ExportFlag
|
||||
presets seccomp.FilterPreset
|
||||
}{
|
||||
{"minimal", true, false, false,
|
||||
new(container.Ops), nil,
|
||||
1000, 100, nil, 0, seccomp.PresetStrict},
|
||||
{"allow", true, true, true,
|
||||
new(container.Ops), nil,
|
||||
1000, 100, nil, 0, seccomp.PresetExt | seccomp.PresetDenyDevel},
|
||||
{"no filter", false, true, true,
|
||||
new(container.Ops), nil,
|
||||
1000, 100, nil, 0, seccomp.PresetExt},
|
||||
{"custom rules", true, true, true,
|
||||
new(container.Ops), nil,
|
||||
1, 31, []seccomp.NativeRule{{seccomp.ScmpSyscall(syscall.SYS_SETUID), seccomp.ScmpErrno(syscall.EPERM), nil}}, 0, seccomp.PresetExt},
|
||||
{"tmpfs", true, false, false,
|
||||
new(container.Ops).
|
||||
Tmpfs(hst.Tmp, 0, 0755),
|
||||
[]*vfs.MountInfoEntry{
|
||||
ent("/", hst.Tmp, "rw,nosuid,nodev,relatime", "tmpfs", "tmpfs", ignore),
|
||||
},
|
||||
9, 9, nil, 0, seccomp.PresetStrict},
|
||||
{"dev", true, true /* go test output is not a tty */, false,
|
||||
new(container.Ops).
|
||||
Dev("/dev").
|
||||
Mqueue("/dev/mqueue"),
|
||||
[]*vfs.MountInfoEntry{
|
||||
ent("/", "/dev", "rw,nosuid,nodev,relatime", "tmpfs", "devtmpfs", ignore),
|
||||
ent("/null", "/dev/null", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/zero", "/dev/zero", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/full", "/dev/full", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/random", "/dev/random", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/urandom", "/dev/urandom", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/tty", "/dev/tty", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
|
||||
ent("/", "/dev/pts", "rw,nosuid,noexec,relatime", "devpts", "devpts", "rw,mode=620,ptmxmode=666"),
|
||||
ent("/", "/dev/mqueue", "rw,nosuid,nodev,noexec,relatime", "mqueue", "mqueue", "rw"),
|
||||
},
|
||||
1971, 100, nil, 0, seccomp.PresetStrict},
|
||||
}
|
||||
|
||||
func TestContainer(t *testing.T) {
|
||||
{
|
||||
oldVerbose := hlog.Load()
|
||||
oldOutput := container.GetOutput()
|
||||
internal.InstallOutput(true)
|
||||
t.Cleanup(func() { hlog.Store(oldVerbose) })
|
||||
t.Cleanup(func() { container.SetOutput(oldOutput) })
|
||||
}
|
||||
|
||||
t.Run("cancel", testContainerCancel(nil, func(t *testing.T, c *container.Container) {
|
||||
wantErr := context.Canceled
|
||||
wantExitCode := 0
|
||||
if err := c.Wait(); !errors.Is(err, wantErr) {
|
||||
hlog.PrintBaseError(err, "wait:")
|
||||
t.Errorf("Wait: error = %v, want %v", err, wantErr)
|
||||
}
|
||||
if ps := c.ProcessState(); ps == nil {
|
||||
t.Errorf("ProcessState unexpectedly returned nil")
|
||||
} else if code := ps.ExitCode(); code != wantExitCode {
|
||||
t.Errorf("ExitCode: %d, want %d", code, wantExitCode)
|
||||
}
|
||||
}))
|
||||
|
||||
t.Run("forward", testContainerCancel(func(c *container.Container) {
|
||||
c.ForwardCancel = true
|
||||
}, func(t *testing.T, c *container.Container) {
|
||||
var exitError *exec.ExitError
|
||||
if err := c.Wait(); !errors.As(err, &exitError) {
|
||||
hlog.PrintBaseError(err, "wait:")
|
||||
t.Errorf("Wait: error = %v", err)
|
||||
}
|
||||
if code := exitError.ExitCode(); code != blockExitCodeInterrupt {
|
||||
t.Errorf("ExitCode: %d, want %d", code, blockExitCodeInterrupt)
|
||||
}
|
||||
}))
|
||||
|
||||
for i, tc := range containerTestCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), helperDefaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
var libPaths []string
|
||||
c := helperNewContainerLibPaths(ctx, &libPaths, "container", strconv.Itoa(i))
|
||||
c.Uid = tc.uid
|
||||
c.Gid = tc.gid
|
||||
c.Hostname = hostnameFromTestCase(tc.name)
|
||||
c.Stdout, c.Stderr = os.Stdout, os.Stderr
|
||||
c.WaitDelay = helperDefaultTimeout
|
||||
*c.Ops = append(*c.Ops, *tc.ops...)
|
||||
c.SeccompRules = tc.rules
|
||||
c.SeccompFlags = tc.flags | seccomp.AllowMultiarch
|
||||
c.SeccompPresets = tc.presets
|
||||
c.SeccompDisable = !tc.filter
|
||||
c.RetainSession = tc.session
|
||||
c.HostNet = tc.net
|
||||
|
||||
c.
|
||||
Tmpfs("/tmp", 0, 0755).
|
||||
Place("/etc/hostname", []byte(c.Hostname))
|
||||
// needs /proc to check mountinfo
|
||||
c.Proc("/proc")
|
||||
|
||||
// mountinfo cannot be resolved directly by helper due to libPaths nondeterminism
|
||||
mnt := make([]*vfs.MountInfoEntry, 0, 3+len(libPaths))
|
||||
mnt = append(mnt,
|
||||
ent("/sysroot", "/", "rw,nosuid,nodev,relatime", "tmpfs", "rootfs", ignore),
|
||||
// Bind(os.Args[0], helperInnerPath, 0)
|
||||
ent(ignore, helperInnerPath, "ro,nosuid,nodev,relatime", ignore, ignore, ignore),
|
||||
)
|
||||
for _, name := range libPaths {
|
||||
// Bind(name, name, 0)
|
||||
mnt = append(mnt, ent(ignore, name, "ro,nosuid,nodev,relatime", ignore, ignore, ignore))
|
||||
}
|
||||
mnt = append(mnt, tc.mnt...)
|
||||
mnt = append(mnt,
|
||||
// Tmpfs("/tmp", 0, 0755)
|
||||
ent("/", "/tmp", "rw,nosuid,nodev,relatime", "tmpfs", "tmpfs", ignore),
|
||||
// Place("/etc/hostname", []byte(hostname))
|
||||
ent(ignore, "/etc/hostname", "ro,nosuid,nodev,relatime", "tmpfs", "rootfs", ignore),
|
||||
// Proc("/proc")
|
||||
ent("/", "/proc", "rw,nosuid,nodev,noexec,relatime", "proc", "proc", "rw"),
|
||||
// Place(pathWantMnt, want.Bytes())
|
||||
ent(ignore, pathWantMnt, "ro,nosuid,nodev,relatime", "tmpfs", "rootfs", ignore),
|
||||
)
|
||||
want := new(bytes.Buffer)
|
||||
if err := gob.NewEncoder(want).Encode(mnt); err != nil {
|
||||
t.Fatalf("cannot serialise expected mount points: %v", err)
|
||||
}
|
||||
c.Place(pathWantMnt, want.Bytes())
|
||||
|
||||
if err := c.Start(); err != nil {
|
||||
hlog.PrintBaseError(err, "start:")
|
||||
t.Fatalf("cannot start container: %v", err)
|
||||
} else if err = c.Serve(); err != nil {
|
||||
hlog.PrintBaseError(err, "serve:")
|
||||
t.Errorf("cannot serve setup params: %v", err)
|
||||
}
|
||||
if err := c.Wait(); err != nil {
|
||||
hlog.PrintBaseError(err, "wait:")
|
||||
t.Fatalf("wait: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func ent(root, target, vfsOptstr, fsType, source, fsOptstr string) *vfs.MountInfoEntry {
|
||||
return &vfs.MountInfoEntry{
|
||||
ID: ignoreV,
|
||||
Parent: ignoreV,
|
||||
Devno: vfs.DevT{ignoreV, ignoreV},
|
||||
Root: root,
|
||||
Target: target,
|
||||
VfsOptstr: vfsOptstr,
|
||||
OptFields: []string{ignore},
|
||||
FsType: fsType,
|
||||
Source: source,
|
||||
FsOptstr: fsOptstr,
|
||||
}
|
||||
}
|
||||
|
||||
func hostnameFromTestCase(name string) string {
|
||||
return "test-" + strings.Join(strings.Fields(name), "-")
|
||||
}
|
||||
|
||||
func testContainerCancel(
|
||||
containerExtra func(c *container.Container),
|
||||
waitCheck func(t *testing.T, c *container.Container),
|
||||
) func(t *testing.T) {
|
||||
return func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), helperDefaultTimeout)
|
||||
|
||||
c := helperNewContainer(ctx, "block")
|
||||
c.Stdout, c.Stderr = os.Stdout, os.Stderr
|
||||
c.WaitDelay = helperDefaultTimeout
|
||||
if containerExtra != nil {
|
||||
containerExtra(c)
|
||||
}
|
||||
|
||||
ready := make(chan struct{})
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
t.Fatalf("cannot pipe: %v", err)
|
||||
} else {
|
||||
c.ExtraFiles = append(c.ExtraFiles, w)
|
||||
go func() {
|
||||
defer close(ready)
|
||||
if _, err = r.Read(make([]byte, 1)); err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if err := c.Start(); err != nil {
|
||||
hlog.PrintBaseError(err, "start:")
|
||||
t.Fatalf("cannot start container: %v", err)
|
||||
} else if err = c.Serve(); err != nil {
|
||||
hlog.PrintBaseError(err, "serve:")
|
||||
t.Errorf("cannot serve setup params: %v", err)
|
||||
}
|
||||
<-ready
|
||||
cancel()
|
||||
waitCheck(t, c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerString(t *testing.T) {
|
||||
c := container.New(t.Context(), "ldd", "/usr/bin/env")
|
||||
c.SeccompFlags |= seccomp.AllowMultiarch
|
||||
c.SeccompRules = seccomp.Preset(
|
||||
seccomp.PresetExt|seccomp.PresetDenyNS|seccomp.PresetDenyTTY,
|
||||
c.SeccompFlags)
|
||||
c.SeccompPresets = seccomp.PresetStrict
|
||||
want := `argv: ["ldd" "/usr/bin/env"], filter: true, rules: 65, flags: 0x1, presets: 0xf`
|
||||
if got := c.String(); got != want {
|
||||
t.Errorf("String: %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
blockExitCodeInterrupt = 2
|
||||
)
|
||||
|
||||
func init() {
|
||||
helperCommands = append(helperCommands, func(c command.Command) {
|
||||
c.Command("block", command.UsageInternal, func(args []string) error {
|
||||
if _, err := os.NewFile(3, "sync").Write([]byte{0}); err != nil {
|
||||
return fmt.Errorf("write to sync pipe: %v", err)
|
||||
}
|
||||
{
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, os.Interrupt)
|
||||
go func() { <-sig; os.Exit(blockExitCodeInterrupt) }()
|
||||
}
|
||||
select {}
|
||||
})
|
||||
|
||||
c.Command("container", command.UsageInternal, func(args []string) error {
|
||||
if len(args) != 1 {
|
||||
return syscall.EINVAL
|
||||
}
|
||||
tc := containerTestCases[0]
|
||||
if i, err := strconv.Atoi(args[0]); err != nil {
|
||||
return fmt.Errorf("cannot parse test case index: %v", err)
|
||||
} else {
|
||||
tc = containerTestCases[i]
|
||||
}
|
||||
|
||||
if uid := syscall.Getuid(); uid != tc.uid {
|
||||
return fmt.Errorf("uid: %d, want %d", uid, tc.uid)
|
||||
}
|
||||
if gid := syscall.Getgid(); gid != tc.gid {
|
||||
return fmt.Errorf("gid: %d, want %d", gid, tc.gid)
|
||||
}
|
||||
|
||||
wantHost := hostnameFromTestCase(tc.name)
|
||||
if host, err := os.Hostname(); err != nil {
|
||||
return fmt.Errorf("cannot get hostname: %v", err)
|
||||
} else if host != wantHost {
|
||||
return fmt.Errorf("hostname: %q, want %q", host, wantHost)
|
||||
}
|
||||
|
||||
if p, err := os.ReadFile("/etc/hostname"); err != nil {
|
||||
return fmt.Errorf("cannot read /etc/hostname: %v", err)
|
||||
} else if string(p) != wantHost {
|
||||
return fmt.Errorf("/etc/hostname: %q, want %q", string(p), wantHost)
|
||||
}
|
||||
|
||||
{
|
||||
var fail bool
|
||||
|
||||
var mnt []*vfs.MountInfoEntry
|
||||
if f, err := os.Open(pathWantMnt); err != nil {
|
||||
return fmt.Errorf("cannot open expected mount points: %v", err)
|
||||
} else if err = gob.NewDecoder(f).Decode(&mnt); err != nil {
|
||||
return fmt.Errorf("cannot parse expected mount points: %v", err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
return fmt.Errorf("cannot close expected mount points: %v", err)
|
||||
}
|
||||
|
||||
var d *vfs.MountInfoDecoder
|
||||
if f, err := os.Open("/proc/self/mountinfo"); err != nil {
|
||||
return fmt.Errorf("cannot open mountinfo: %v", err)
|
||||
} else {
|
||||
d = vfs.NewMountInfoDecoder(f)
|
||||
}
|
||||
|
||||
i := 0
|
||||
for cur := range d.Entries() {
|
||||
if i == len(mnt) {
|
||||
return fmt.Errorf("got more than %d entries", len(mnt))
|
||||
}
|
||||
|
||||
// ugly hack but should be reliable and is less likely to false negative than comparing by parsed flags
|
||||
cur.VfsOptstr = strings.TrimSuffix(cur.VfsOptstr, ",relatime")
|
||||
cur.VfsOptstr = strings.TrimSuffix(cur.VfsOptstr, ",noatime")
|
||||
mnt[i].VfsOptstr = strings.TrimSuffix(mnt[i].VfsOptstr, ",relatime")
|
||||
mnt[i].VfsOptstr = strings.TrimSuffix(mnt[i].VfsOptstr, ",noatime")
|
||||
|
||||
if !cur.EqualWithIgnore(mnt[i], "\x00") {
|
||||
fail = true
|
||||
log.Printf("[FAIL] %s", cur)
|
||||
} else {
|
||||
log.Printf("[ OK ] %s", cur)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
if err := d.Err(); err != nil {
|
||||
return fmt.Errorf("cannot parse mountinfo: %v", err)
|
||||
}
|
||||
|
||||
if i != len(mnt) {
|
||||
return fmt.Errorf("got %d entries, want %d", i, len(mnt))
|
||||
}
|
||||
|
||||
if fail {
|
||||
return errors.New("one or more mountinfo entries do not match")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package internal
|
||||
package container
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -15,7 +13,7 @@ var (
|
||||
|
||||
func copyExecutable() {
|
||||
if name, err := os.Executable(); err != nil {
|
||||
fmsg.BeforeExit()
|
||||
msg.BeforeExit()
|
||||
log.Fatalf("cannot read executable path: %v", err)
|
||||
} else {
|
||||
executable = name
|
||||
17
container/executable_test.go
Normal file
17
container/executable_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package container_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container"
|
||||
)
|
||||
|
||||
func TestExecutable(t *testing.T) {
|
||||
for i := 0; i < 16; i++ {
|
||||
if got := container.MustExecutable(); got != os.Args[0] {
|
||||
t.Errorf("MustExecutable: %q, want %q",
|
||||
got, os.Args[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
381
container/init.go
Normal file
381
container/init.go
Normal file
@@ -0,0 +1,381 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path"
|
||||
"runtime"
|
||||
"strconv"
|
||||
. "syscall"
|
||||
"time"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
)
|
||||
|
||||
const (
|
||||
/* intermediate tmpfs mount point
|
||||
|
||||
this path might seem like a weird choice, however there are many good reasons to use it:
|
||||
- the contents of this path is never exposed to the container:
|
||||
the tmpfs root established here effectively becomes anonymous after pivot_root
|
||||
- it is safe to assume this path exists and is a directory:
|
||||
this program will not work correctly without a proper /proc and neither will most others
|
||||
- this path belongs to the container init:
|
||||
the container init is not any more privileged or trusted than the rest of the container
|
||||
- this path is only accessible by init and root:
|
||||
the container init sets SUID_DUMP_DISABLE and terminates if that fails;
|
||||
|
||||
it should be noted that none of this should become relevant at any point since the resulting
|
||||
intermediate root tmpfs should be effectively anonymous */
|
||||
intermediateHostPath = "/proc/self/fd"
|
||||
|
||||
// setup params file descriptor
|
||||
setupEnv = "HAKUREI_SETUP"
|
||||
)
|
||||
|
||||
type initParams struct {
|
||||
Params
|
||||
|
||||
HostUid, HostGid int
|
||||
// extra files count
|
||||
Count int
|
||||
// verbosity pass through
|
||||
Verbose bool
|
||||
}
|
||||
|
||||
func Init(prepare func(prefix string), setVerbose func(verbose bool)) {
|
||||
runtime.LockOSThread()
|
||||
prepare("init")
|
||||
|
||||
if os.Getpid() != 1 {
|
||||
log.Fatal("this process must run as pid 1")
|
||||
}
|
||||
|
||||
var (
|
||||
params initParams
|
||||
closeSetup func() error
|
||||
setupFile *os.File
|
||||
offsetSetup int
|
||||
)
|
||||
if f, err := Receive(setupEnv, ¶ms, &setupFile); err != nil {
|
||||
if errors.Is(err, ErrInvalid) {
|
||||
log.Fatal("invalid setup descriptor")
|
||||
}
|
||||
if errors.Is(err, ErrNotSet) {
|
||||
log.Fatal("HAKUREI_SETUP not set")
|
||||
}
|
||||
|
||||
log.Fatalf("cannot decode init setup payload: %v", err)
|
||||
} else {
|
||||
if params.Ops == nil {
|
||||
log.Fatal("invalid setup parameters")
|
||||
}
|
||||
if params.ParentPerm == 0 {
|
||||
params.ParentPerm = 0755
|
||||
}
|
||||
|
||||
setVerbose(params.Verbose)
|
||||
msg.Verbose("received setup parameters")
|
||||
closeSetup = f
|
||||
offsetSetup = int(setupFile.Fd() + 1)
|
||||
}
|
||||
|
||||
// write uid/gid map here so parent does not need to set dumpable
|
||||
if err := SetDumpable(SUID_DUMP_USER); err != nil {
|
||||
log.Fatalf("cannot set SUID_DUMP_USER: %s", err)
|
||||
}
|
||||
if err := os.WriteFile("/proc/self/uid_map",
|
||||
append([]byte{}, strconv.Itoa(params.Uid)+" "+strconv.Itoa(params.HostUid)+" 1\n"...),
|
||||
0); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
if err := os.WriteFile("/proc/self/setgroups",
|
||||
[]byte("deny\n"),
|
||||
0); err != nil && !os.IsNotExist(err) {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
if err := os.WriteFile("/proc/self/gid_map",
|
||||
append([]byte{}, strconv.Itoa(params.Gid)+" "+strconv.Itoa(params.HostGid)+" 1\n"...),
|
||||
0); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
if err := SetDumpable(SUID_DUMP_DISABLE); err != nil {
|
||||
log.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
|
||||
}
|
||||
|
||||
oldmask := Umask(0)
|
||||
if params.Hostname != "" {
|
||||
if err := Sethostname([]byte(params.Hostname)); err != nil {
|
||||
log.Fatalf("cannot set hostname: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// cache sysctl before pivot_root
|
||||
LastCap()
|
||||
|
||||
if err := Mount("", "/", "", MS_SILENT|MS_SLAVE|MS_REC, ""); err != nil {
|
||||
log.Fatalf("cannot make / rslave: %v", err)
|
||||
}
|
||||
|
||||
for i, op := range *params.Ops {
|
||||
if op == nil {
|
||||
log.Fatalf("invalid op %d", i)
|
||||
}
|
||||
|
||||
if err := op.early(¶ms.Params); err != nil {
|
||||
msg.PrintBaseErr(err,
|
||||
fmt.Sprintf("cannot prepare op %d:", i))
|
||||
msg.BeforeExit()
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
if err := Mount("rootfs", intermediateHostPath, "tmpfs", MS_NODEV|MS_NOSUID, ""); err != nil {
|
||||
log.Fatalf("cannot mount intermediate root: %v", err)
|
||||
}
|
||||
if err := os.Chdir(intermediateHostPath); err != nil {
|
||||
log.Fatalf("cannot enter base path: %v", err)
|
||||
}
|
||||
|
||||
if err := os.Mkdir(sysrootDir, 0755); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
if err := Mount(sysrootDir, sysrootDir, "", MS_SILENT|MS_MGC_VAL|MS_BIND|MS_REC, ""); err != nil {
|
||||
log.Fatalf("cannot bind sysroot: %v", err)
|
||||
}
|
||||
|
||||
if err := os.Mkdir(hostDir, 0755); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
// pivot_root uncovers intermediateHostPath in hostDir
|
||||
if err := PivotRoot(intermediateHostPath, hostDir); err != nil {
|
||||
log.Fatalf("cannot pivot into intermediate root: %v", err)
|
||||
}
|
||||
if err := os.Chdir("/"); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
for i, op := range *params.Ops {
|
||||
// ops already checked during early setup
|
||||
msg.Verbosef("%s %s", op.prefix(), op)
|
||||
if err := op.apply(¶ms.Params); err != nil {
|
||||
msg.PrintBaseErr(err,
|
||||
fmt.Sprintf("cannot apply op %d:", i))
|
||||
msg.BeforeExit()
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// setup requiring host root complete at this point
|
||||
if err := Mount(hostDir, hostDir, "", MS_SILENT|MS_REC|MS_PRIVATE, ""); err != nil {
|
||||
log.Fatalf("cannot make host root rprivate: %v", err)
|
||||
}
|
||||
if err := Unmount(hostDir, MNT_DETACH); err != nil {
|
||||
log.Fatalf("cannot unmount host root: %v", err)
|
||||
}
|
||||
|
||||
{
|
||||
var fd int
|
||||
if err := IgnoringEINTR(func() (err error) {
|
||||
fd, err = Open("/", O_DIRECTORY|O_RDONLY, 0)
|
||||
return
|
||||
}); err != nil {
|
||||
log.Fatalf("cannot open intermediate root: %v", err)
|
||||
}
|
||||
if err := os.Chdir(sysrootPath); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
if err := PivotRoot(".", "."); err != nil {
|
||||
log.Fatalf("cannot pivot into sysroot: %v", err)
|
||||
}
|
||||
if err := Fchdir(fd); err != nil {
|
||||
log.Fatalf("cannot re-enter intermediate root: %v", err)
|
||||
}
|
||||
if err := Unmount(".", MNT_DETACH); err != nil {
|
||||
log.Fatalf("cannot unmount intemediate root: %v", err)
|
||||
}
|
||||
if err := os.Chdir("/"); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
if err := Close(fd); err != nil {
|
||||
log.Fatalf("cannot close intermediate root: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, _, errno := Syscall(SYS_PRCTL, PR_SET_NO_NEW_PRIVS, 1, 0); errno != 0 {
|
||||
log.Fatalf("prctl(PR_SET_NO_NEW_PRIVS): %v", errno)
|
||||
}
|
||||
|
||||
if _, _, errno := Syscall(SYS_PRCTL, PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0); errno != 0 {
|
||||
log.Fatalf("cannot clear the ambient capability set: %v", errno)
|
||||
}
|
||||
for i := uintptr(0); i <= LastCap(); i++ {
|
||||
if params.Privileged && i == CAP_SYS_ADMIN {
|
||||
continue
|
||||
}
|
||||
if _, _, errno := Syscall(SYS_PRCTL, PR_CAPBSET_DROP, i, 0); errno != 0 {
|
||||
log.Fatalf("cannot drop capability from bonding set: %v", errno)
|
||||
}
|
||||
}
|
||||
|
||||
var keep [2]uint32
|
||||
if params.Privileged {
|
||||
keep[capToIndex(CAP_SYS_ADMIN)] |= capToMask(CAP_SYS_ADMIN)
|
||||
|
||||
if _, _, errno := Syscall(SYS_PRCTL, PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_SYS_ADMIN); errno != 0 {
|
||||
log.Fatalf("cannot raise CAP_SYS_ADMIN: %v", errno)
|
||||
}
|
||||
}
|
||||
if err := capset(
|
||||
&capHeader{_LINUX_CAPABILITY_VERSION_3, 0},
|
||||
&[2]capData{{0, keep[0], keep[0]}, {0, keep[1], keep[1]}},
|
||||
); err != nil {
|
||||
log.Fatalf("cannot capset: %v", err)
|
||||
}
|
||||
|
||||
if !params.SeccompDisable {
|
||||
rules := params.SeccompRules
|
||||
if len(rules) == 0 { // non-empty rules slice always overrides presets
|
||||
msg.Verbosef("resolving presets %#x", params.SeccompPresets)
|
||||
rules = seccomp.Preset(params.SeccompPresets, params.SeccompFlags)
|
||||
}
|
||||
if err := seccomp.Load(rules, params.SeccompFlags); err != nil {
|
||||
log.Fatalf("cannot load syscall filter: %v", err)
|
||||
}
|
||||
msg.Verbosef("%d filter rules loaded", len(rules))
|
||||
} else {
|
||||
msg.Verbose("syscall filter not configured")
|
||||
}
|
||||
|
||||
extraFiles := make([]*os.File, params.Count)
|
||||
for i := range extraFiles {
|
||||
// setup fd is placed before all extra files
|
||||
extraFiles[i] = os.NewFile(uintptr(offsetSetup+i), "extra file "+strconv.Itoa(i))
|
||||
}
|
||||
Umask(oldmask)
|
||||
|
||||
cmd := exec.Command(params.Path)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
cmd.Args = params.Args
|
||||
cmd.Env = params.Env
|
||||
cmd.ExtraFiles = extraFiles
|
||||
cmd.Dir = params.Dir
|
||||
|
||||
msg.Verbosef("starting initial program %s", params.Path)
|
||||
if err := cmd.Start(); err != nil {
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
msg.Suspend()
|
||||
|
||||
if err := closeSetup(); err != nil {
|
||||
log.Printf("cannot close setup pipe: %v", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
type winfo struct {
|
||||
wpid int
|
||||
wstatus WaitStatus
|
||||
}
|
||||
info := make(chan winfo, 1)
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
var (
|
||||
err error
|
||||
wpid = -2
|
||||
wstatus WaitStatus
|
||||
)
|
||||
|
||||
// keep going until no child process is left
|
||||
for wpid != -1 {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if wpid != -2 {
|
||||
info <- winfo{wpid, wstatus}
|
||||
}
|
||||
|
||||
err = EINTR
|
||||
for errors.Is(err, EINTR) {
|
||||
wpid, err = Wait4(-1, &wstatus, 0, nil)
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, ECHILD) {
|
||||
log.Printf("unexpected wait4 response: %v", err)
|
||||
}
|
||||
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// handle signals to dump withheld messages
|
||||
sig := make(chan os.Signal, 2)
|
||||
signal.Notify(sig, os.Interrupt, CancelSignal)
|
||||
|
||||
// closed after residualProcessTimeout has elapsed after initial process death
|
||||
timeout := make(chan struct{})
|
||||
|
||||
r := 2
|
||||
for {
|
||||
select {
|
||||
case s := <-sig:
|
||||
if msg.Resume() {
|
||||
msg.Verbosef("%s after process start", s.String())
|
||||
} else {
|
||||
msg.Verbosef("got %s", s.String())
|
||||
}
|
||||
if s == CancelSignal && params.ForwardCancel && cmd.Process != nil {
|
||||
msg.Verbose("forwarding context cancellation")
|
||||
if err := cmd.Process.Signal(os.Interrupt); err != nil {
|
||||
log.Printf("cannot forward cancellation: %v", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
os.Exit(0)
|
||||
case w := <-info:
|
||||
if w.wpid == cmd.Process.Pid {
|
||||
// initial process exited, output is most likely available again
|
||||
msg.Resume()
|
||||
|
||||
switch {
|
||||
case w.wstatus.Exited():
|
||||
r = w.wstatus.ExitStatus()
|
||||
msg.Verbosef("initial process exited with code %d", w.wstatus.ExitStatus())
|
||||
case w.wstatus.Signaled():
|
||||
r = 128 + int(w.wstatus.Signal())
|
||||
msg.Verbosef("initial process exited with signal %s", w.wstatus.Signal())
|
||||
default:
|
||||
r = 255
|
||||
msg.Verbosef("initial process exited with status %#x", w.wstatus)
|
||||
}
|
||||
|
||||
go func() { time.Sleep(params.AdoptWaitDelay); close(timeout) }()
|
||||
}
|
||||
case <-done:
|
||||
msg.BeforeExit()
|
||||
os.Exit(r)
|
||||
case <-timeout:
|
||||
log.Println("timeout exceeded waiting for lingering processes")
|
||||
msg.BeforeExit()
|
||||
os.Exit(r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const initName = "init"
|
||||
|
||||
// TryArgv0 calls [Init] if the last element of argv0 is "init".
|
||||
func TryArgv0(v Msg, prepare func(prefix string), setVerbose func(verbose bool)) {
|
||||
if len(os.Args) > 0 && path.Base(os.Args[0]) == initName {
|
||||
msg = v
|
||||
Init(prepare, setVerbose)
|
||||
msg.BeforeExit()
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
69
container/init_test.go
Normal file
69
container/init_test.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package container_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hakurei.app/command"
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/internal"
|
||||
"hakurei.app/internal/hlog"
|
||||
"hakurei.app/ldd"
|
||||
)
|
||||
|
||||
const (
|
||||
envDoCheck = "HAKUREI_TEST_DO_CHECK"
|
||||
|
||||
helperDefaultTimeout = 5 * time.Second
|
||||
helperInnerPath = "/usr/bin/helper"
|
||||
)
|
||||
|
||||
var helperCommands []func(c command.Command)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
container.TryArgv0(hlog.Output{}, hlog.Prepare, internal.InstallOutput)
|
||||
|
||||
if os.Getenv(envDoCheck) == "1" {
|
||||
c := command.New(os.Stderr, log.Printf, "helper", func(args []string) error {
|
||||
log.SetFlags(0)
|
||||
log.SetPrefix("helper: ")
|
||||
return nil
|
||||
})
|
||||
for _, f := range helperCommands {
|
||||
f(c)
|
||||
}
|
||||
c.MustParse(os.Args[1:], func(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func helperNewContainerLibPaths(ctx context.Context, libPaths *[]string, args ...string) (c *container.Container) {
|
||||
c = container.New(ctx, helperInnerPath, args...)
|
||||
c.Env = append(c.Env, envDoCheck+"=1")
|
||||
c.Bind(os.Args[0], helperInnerPath, 0)
|
||||
|
||||
// in case test has cgo enabled
|
||||
if entries, err := ldd.Exec(ctx, os.Args[0]); err != nil {
|
||||
log.Fatalf("ldd: %v", err)
|
||||
} else {
|
||||
*libPaths = ldd.Path(entries)
|
||||
}
|
||||
for _, name := range *libPaths {
|
||||
c.Bind(name, name, 0)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func helperNewContainer(ctx context.Context, args ...string) (c *container.Container) {
|
||||
return helperNewContainerLibPaths(ctx, new([]string), args...)
|
||||
}
|
||||
123
container/mount.go
Normal file
123
container/mount.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
. "syscall"
|
||||
|
||||
"hakurei.app/container/vfs"
|
||||
)
|
||||
|
||||
func (p *procPaths) bindMount(source, target string, flags uintptr, eq bool) error {
|
||||
if eq {
|
||||
msg.Verbosef("resolved %q flags %#x", target, flags)
|
||||
} else {
|
||||
msg.Verbosef("resolved %q on %q flags %#x", source, target, flags)
|
||||
}
|
||||
|
||||
if err := Mount(source, target, "", MS_SILENT|MS_BIND|flags&MS_REC, ""); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
fmt.Sprintf("cannot mount %q on %q:", source, target))
|
||||
}
|
||||
|
||||
var targetFinal string
|
||||
if v, err := filepath.EvalSymlinks(target); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else {
|
||||
targetFinal = v
|
||||
if targetFinal != target {
|
||||
msg.Verbosef("target resolves to %q", targetFinal)
|
||||
}
|
||||
}
|
||||
|
||||
// final target path according to the kernel through proc
|
||||
var targetKFinal string
|
||||
{
|
||||
var destFd int
|
||||
if err := IgnoringEINTR(func() (err error) {
|
||||
destFd, err = Open(targetFinal, O_PATH|O_CLOEXEC, 0)
|
||||
return
|
||||
}); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
fmt.Sprintf("cannot open %q:", targetFinal))
|
||||
}
|
||||
if v, err := os.Readlink(p.fd(destFd)); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else if err = Close(destFd); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
fmt.Sprintf("cannot close %q:", targetFinal))
|
||||
} else {
|
||||
targetKFinal = v
|
||||
}
|
||||
}
|
||||
|
||||
mf := MS_NOSUID | flags&MS_NODEV | flags&MS_RDONLY
|
||||
return hostProc.mountinfo(func(d *vfs.MountInfoDecoder) error {
|
||||
n, err := d.Unfold(targetKFinal)
|
||||
if err != nil {
|
||||
if errors.Is(err, ESTALE) {
|
||||
return msg.WrapErr(err,
|
||||
fmt.Sprintf("mount point %q never appeared in mountinfo", targetKFinal))
|
||||
}
|
||||
return wrapErrSuffix(err,
|
||||
"cannot unfold mount hierarchy:")
|
||||
}
|
||||
|
||||
if err = remountWithFlags(n, mf); err != nil {
|
||||
return err
|
||||
}
|
||||
if flags&MS_REC == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for cur := range n.Collective() {
|
||||
err = remountWithFlags(cur, mf)
|
||||
if err != nil && !errors.Is(err, EACCES) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func remountWithFlags(n *vfs.MountInfoNode, mf uintptr) error {
|
||||
kf, unmatched := n.Flags()
|
||||
if len(unmatched) != 0 {
|
||||
msg.Verbosef("unmatched vfs options: %q", unmatched)
|
||||
}
|
||||
|
||||
if kf&mf != mf {
|
||||
return wrapErrSuffix(
|
||||
Mount("none", n.Clean, "", MS_SILENT|MS_BIND|MS_REMOUNT|kf|mf, ""),
|
||||
fmt.Sprintf("cannot remount %q:", n.Clean))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mountTmpfs(fsname, name string, size int, perm os.FileMode) error {
|
||||
target := toSysroot(name)
|
||||
if err := os.MkdirAll(target, parentPerm(perm)); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
opt := fmt.Sprintf("mode=%#o", perm)
|
||||
if size > 0 {
|
||||
opt += fmt.Sprintf(",size=%d", size)
|
||||
}
|
||||
return wrapErrSuffix(
|
||||
Mount(fsname, target, "tmpfs", MS_NOSUID|MS_NODEV, opt),
|
||||
fmt.Sprintf("cannot mount tmpfs on %q:", name))
|
||||
}
|
||||
|
||||
func parentPerm(perm os.FileMode) os.FileMode {
|
||||
pperm := 0755
|
||||
if perm&0070 == 0 {
|
||||
pperm &= ^0050
|
||||
}
|
||||
if perm&0007 == 0 {
|
||||
pperm &= ^0005
|
||||
}
|
||||
return os.FileMode(pperm)
|
||||
}
|
||||
43
container/msg.go
Normal file
43
container/msg.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type Msg interface {
|
||||
IsVerbose() bool
|
||||
Verbose(v ...any)
|
||||
Verbosef(format string, v ...any)
|
||||
WrapErr(err error, a ...any) error
|
||||
PrintBaseErr(err error, fallback string)
|
||||
|
||||
Suspend()
|
||||
Resume() bool
|
||||
|
||||
BeforeExit()
|
||||
}
|
||||
|
||||
type DefaultMsg struct{ inactive atomic.Bool }
|
||||
|
||||
func (msg *DefaultMsg) IsVerbose() bool { return true }
|
||||
func (msg *DefaultMsg) Verbose(v ...any) {
|
||||
if !msg.inactive.Load() {
|
||||
log.Println(v...)
|
||||
}
|
||||
}
|
||||
func (msg *DefaultMsg) Verbosef(format string, v ...any) {
|
||||
if !msg.inactive.Load() {
|
||||
log.Printf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
func (msg *DefaultMsg) WrapErr(err error, a ...any) error {
|
||||
log.Println(a...)
|
||||
return err
|
||||
}
|
||||
func (msg *DefaultMsg) PrintBaseErr(err error, fallback string) { log.Println(fallback, err) }
|
||||
|
||||
func (msg *DefaultMsg) Suspend() { msg.inactive.Store(true) }
|
||||
func (msg *DefaultMsg) Resume() bool { return msg.inactive.CompareAndSwap(true, false) }
|
||||
func (msg *DefaultMsg) BeforeExit() {}
|
||||
500
container/ops.go
Normal file
500
container/ops.go
Normal file
@@ -0,0 +1,500 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
. "syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type (
|
||||
Ops []Op
|
||||
|
||||
// Op is a generic setup step ran inside the container init.
|
||||
// Implementations of this interface are sent as a stream of gobs.
|
||||
Op interface {
|
||||
// early is called in host root.
|
||||
early(params *Params) error
|
||||
// apply is called in intermediate root.
|
||||
apply(params *Params) error
|
||||
|
||||
prefix() string
|
||||
Is(op Op) bool
|
||||
fmt.Stringer
|
||||
}
|
||||
)
|
||||
|
||||
// Grow grows the slice Ops points to using [slices.Grow].
|
||||
func (f *Ops) Grow(n int) { *f = slices.Grow(*f, n) }
|
||||
|
||||
func init() { gob.Register(new(BindMountOp)) }
|
||||
|
||||
// Bind appends an [Op] that bind mounts host path [BindMountOp.Source] on container path [BindMountOp.Target].
|
||||
func (f *Ops) Bind(source, target string, flags int) *Ops {
|
||||
*f = append(*f, &BindMountOp{source, "", target, flags})
|
||||
return f
|
||||
}
|
||||
|
||||
type BindMountOp struct {
|
||||
Source, SourceFinal, Target string
|
||||
|
||||
Flags int
|
||||
}
|
||||
|
||||
const (
|
||||
// BindOptional skips nonexistent host paths.
|
||||
BindOptional = 1 << iota
|
||||
// BindWritable mounts filesystem read-write.
|
||||
BindWritable
|
||||
// BindDevice allows access to devices (special files) on this filesystem.
|
||||
BindDevice
|
||||
)
|
||||
|
||||
func (b *BindMountOp) early(*Params) error {
|
||||
if !path.IsAbs(b.Source) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", b.Source))
|
||||
}
|
||||
|
||||
if v, err := filepath.EvalSymlinks(b.Source); err != nil {
|
||||
if os.IsNotExist(err) && b.Flags&BindOptional != 0 {
|
||||
b.SourceFinal = "\x00"
|
||||
return nil
|
||||
}
|
||||
return wrapErrSelf(err)
|
||||
} else {
|
||||
b.SourceFinal = v
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BindMountOp) apply(*Params) error {
|
||||
if b.SourceFinal == "\x00" {
|
||||
if b.Flags&BindOptional == 0 {
|
||||
// unreachable
|
||||
return EBADE
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if !path.IsAbs(b.SourceFinal) || !path.IsAbs(b.Target) {
|
||||
return msg.WrapErr(EBADE, "path is not absolute")
|
||||
}
|
||||
|
||||
source := toHost(b.SourceFinal)
|
||||
target := toSysroot(b.Target)
|
||||
|
||||
// this perm value emulates bwrap behaviour as it clears bits from 0755 based on
|
||||
// op->perms which is never set for any bind setup op so always results in 0700
|
||||
if fi, err := os.Stat(source); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else if fi.IsDir() {
|
||||
if err = os.MkdirAll(target, 0700); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
} else if err = ensureFile(target, 0444, 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var flags uintptr = MS_REC
|
||||
if b.Flags&BindWritable == 0 {
|
||||
flags |= MS_RDONLY
|
||||
}
|
||||
if b.Flags&BindDevice == 0 {
|
||||
flags |= MS_NODEV
|
||||
}
|
||||
|
||||
return hostProc.bindMount(source, target, flags, b.SourceFinal == b.Target)
|
||||
}
|
||||
|
||||
func (b *BindMountOp) Is(op Op) bool { vb, ok := op.(*BindMountOp); return ok && *b == *vb }
|
||||
func (*BindMountOp) prefix() string { return "mounting" }
|
||||
func (b *BindMountOp) String() string {
|
||||
if b.Source == b.Target {
|
||||
return fmt.Sprintf("%q flags %#x", b.Source, b.Flags)
|
||||
}
|
||||
return fmt.Sprintf("%q on %q flags %#x", b.Source, b.Target, b.Flags&BindWritable)
|
||||
}
|
||||
|
||||
func init() { gob.Register(new(MountProcOp)) }
|
||||
|
||||
// Proc appends an [Op] that mounts a private instance of proc.
|
||||
func (f *Ops) Proc(dest string) *Ops {
|
||||
*f = append(*f, MountProcOp(dest))
|
||||
return f
|
||||
}
|
||||
|
||||
type MountProcOp string
|
||||
|
||||
func (p MountProcOp) early(*Params) error { return nil }
|
||||
func (p MountProcOp) apply(params *Params) error {
|
||||
v := string(p)
|
||||
|
||||
if !path.IsAbs(v) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", v))
|
||||
}
|
||||
|
||||
target := toSysroot(v)
|
||||
if err := os.MkdirAll(target, params.ParentPerm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
return wrapErrSuffix(Mount("proc", target, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, ""),
|
||||
fmt.Sprintf("cannot mount proc on %q:", v))
|
||||
}
|
||||
|
||||
func (p MountProcOp) Is(op Op) bool { vp, ok := op.(MountProcOp); return ok && p == vp }
|
||||
func (MountProcOp) prefix() string { return "mounting" }
|
||||
func (p MountProcOp) String() string { return fmt.Sprintf("proc on %q", string(p)) }
|
||||
|
||||
func init() { gob.Register(new(MountDevOp)) }
|
||||
|
||||
// Dev appends an [Op] that mounts a subset of host /dev.
|
||||
func (f *Ops) Dev(dest string) *Ops {
|
||||
*f = append(*f, MountDevOp(dest))
|
||||
return f
|
||||
}
|
||||
|
||||
type MountDevOp string
|
||||
|
||||
func (d MountDevOp) early(*Params) error { return nil }
|
||||
func (d MountDevOp) apply(params *Params) error {
|
||||
v := string(d)
|
||||
|
||||
if !path.IsAbs(v) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", v))
|
||||
}
|
||||
target := toSysroot(v)
|
||||
|
||||
if err := mountTmpfs("devtmpfs", v, 0, params.ParentPerm); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range []string{"null", "zero", "full", "random", "urandom", "tty"} {
|
||||
targetPath := toSysroot(path.Join(v, name))
|
||||
if err := ensureFile(targetPath, 0444, params.ParentPerm); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := hostProc.bindMount(
|
||||
toHost("/dev/"+name),
|
||||
targetPath,
|
||||
0,
|
||||
true,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i, name := range []string{"stdin", "stdout", "stderr"} {
|
||||
if err := os.Symlink(
|
||||
"/proc/self/fd/"+string(rune(i+'0')),
|
||||
path.Join(target, name),
|
||||
); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
}
|
||||
for _, pair := range [][2]string{
|
||||
{"/proc/self/fd", "fd"},
|
||||
{"/proc/kcore", "core"},
|
||||
{"pts/ptmx", "ptmx"},
|
||||
} {
|
||||
if err := os.Symlink(pair[0], path.Join(target, pair[1])); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
}
|
||||
|
||||
devPtsPath := path.Join(target, "pts")
|
||||
for _, name := range []string{path.Join(target, "shm"), devPtsPath} {
|
||||
if err := os.Mkdir(name, params.ParentPerm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := Mount("devpts", devPtsPath, "devpts", MS_NOSUID|MS_NOEXEC,
|
||||
"newinstance,ptmxmode=0666,mode=620"); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
fmt.Sprintf("cannot mount devpts on %q:", devPtsPath))
|
||||
}
|
||||
|
||||
if params.RetainSession {
|
||||
var buf [8]byte
|
||||
if _, _, errno := Syscall(SYS_IOCTL, 1, TIOCGWINSZ, uintptr(unsafe.Pointer(&buf[0]))); errno == 0 {
|
||||
consolePath := toSysroot(path.Join(v, "console"))
|
||||
if err := ensureFile(consolePath, 0444, params.ParentPerm); err != nil {
|
||||
return err
|
||||
}
|
||||
if name, err := os.Readlink(hostProc.stdout()); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else if err = hostProc.bindMount(
|
||||
toHost(name),
|
||||
consolePath,
|
||||
0,
|
||||
false,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d MountDevOp) Is(op Op) bool { vd, ok := op.(MountDevOp); return ok && d == vd }
|
||||
func (MountDevOp) prefix() string { return "mounting" }
|
||||
func (d MountDevOp) String() string { return fmt.Sprintf("dev on %q", string(d)) }
|
||||
|
||||
func init() { gob.Register(new(MountMqueueOp)) }
|
||||
|
||||
// Mqueue appends an [Op] that mounts a private instance of mqueue.
|
||||
func (f *Ops) Mqueue(dest string) *Ops {
|
||||
*f = append(*f, MountMqueueOp(dest))
|
||||
return f
|
||||
}
|
||||
|
||||
type MountMqueueOp string
|
||||
|
||||
func (m MountMqueueOp) early(*Params) error { return nil }
|
||||
func (m MountMqueueOp) apply(params *Params) error {
|
||||
v := string(m)
|
||||
|
||||
if !path.IsAbs(v) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", v))
|
||||
}
|
||||
|
||||
target := toSysroot(v)
|
||||
if err := os.MkdirAll(target, params.ParentPerm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
return wrapErrSuffix(Mount("mqueue", target, "mqueue", MS_NOSUID|MS_NOEXEC|MS_NODEV, ""),
|
||||
fmt.Sprintf("cannot mount mqueue on %q:", v))
|
||||
}
|
||||
|
||||
func (m MountMqueueOp) Is(op Op) bool { vm, ok := op.(MountMqueueOp); return ok && m == vm }
|
||||
func (MountMqueueOp) prefix() string { return "mounting" }
|
||||
func (m MountMqueueOp) String() string { return fmt.Sprintf("mqueue on %q", string(m)) }
|
||||
|
||||
func init() { gob.Register(new(MountTmpfsOp)) }
|
||||
|
||||
// Tmpfs appends an [Op] that mounts tmpfs on container path [MountTmpfsOp.Path].
|
||||
func (f *Ops) Tmpfs(dest string, size int, perm os.FileMode) *Ops {
|
||||
*f = append(*f, &MountTmpfsOp{dest, size, perm})
|
||||
return f
|
||||
}
|
||||
|
||||
type MountTmpfsOp struct {
|
||||
Path string
|
||||
Size int
|
||||
Perm os.FileMode
|
||||
}
|
||||
|
||||
func (t *MountTmpfsOp) early(*Params) error { return nil }
|
||||
func (t *MountTmpfsOp) apply(*Params) error {
|
||||
if !path.IsAbs(t.Path) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", t.Path))
|
||||
}
|
||||
if t.Size < 0 || t.Size > math.MaxUint>>1 {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("size %d out of bounds", t.Size))
|
||||
}
|
||||
return mountTmpfs("tmpfs", t.Path, t.Size, t.Perm)
|
||||
}
|
||||
|
||||
func (t *MountTmpfsOp) Is(op Op) bool { vt, ok := op.(*MountTmpfsOp); return ok && *t == *vt }
|
||||
func (*MountTmpfsOp) prefix() string { return "mounting" }
|
||||
func (t *MountTmpfsOp) String() string { return fmt.Sprintf("tmpfs on %q size %d", t.Path, t.Size) }
|
||||
|
||||
func init() { gob.Register(new(SymlinkOp)) }
|
||||
|
||||
// Link appends an [Op] that creates a symlink in the container filesystem.
|
||||
func (f *Ops) Link(target, linkName string) *Ops {
|
||||
*f = append(*f, &SymlinkOp{target, linkName})
|
||||
return f
|
||||
}
|
||||
|
||||
type SymlinkOp [2]string
|
||||
|
||||
func (l *SymlinkOp) early(*Params) error {
|
||||
if strings.HasPrefix(l[0], "*") {
|
||||
l[0] = l[0][1:]
|
||||
if !path.IsAbs(l[0]) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", l[0]))
|
||||
}
|
||||
if name, err := os.Readlink(l[0]); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else {
|
||||
l[0] = name
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (l *SymlinkOp) apply(params *Params) error {
|
||||
// symlink target is an arbitrary path value, so only validate link name here
|
||||
if !path.IsAbs(l[1]) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", l[1]))
|
||||
}
|
||||
|
||||
target := toSysroot(l[1])
|
||||
if err := os.MkdirAll(path.Dir(target), params.ParentPerm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
if err := os.Symlink(l[0], target); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *SymlinkOp) Is(op Op) bool { vl, ok := op.(*SymlinkOp); return ok && *l == *vl }
|
||||
func (*SymlinkOp) prefix() string { return "creating" }
|
||||
func (l *SymlinkOp) String() string { return fmt.Sprintf("symlink on %q target %q", l[1], l[0]) }
|
||||
|
||||
func init() { gob.Register(new(MkdirOp)) }
|
||||
|
||||
// Mkdir appends an [Op] that creates a directory in the container filesystem.
|
||||
func (f *Ops) Mkdir(dest string, perm os.FileMode) *Ops {
|
||||
*f = append(*f, &MkdirOp{dest, perm})
|
||||
return f
|
||||
}
|
||||
|
||||
type MkdirOp struct {
|
||||
Path string
|
||||
Perm os.FileMode
|
||||
}
|
||||
|
||||
func (m *MkdirOp) early(*Params) error { return nil }
|
||||
func (m *MkdirOp) apply(*Params) error {
|
||||
if !path.IsAbs(m.Path) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", m.Path))
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(toSysroot(m.Path), m.Perm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MkdirOp) Is(op Op) bool { vm, ok := op.(*MkdirOp); return ok && m == vm }
|
||||
func (*MkdirOp) prefix() string { return "creating" }
|
||||
func (m *MkdirOp) String() string { return fmt.Sprintf("directory %q perm %s", m.Path, m.Perm) }
|
||||
|
||||
func init() { gob.Register(new(TmpfileOp)) }
|
||||
|
||||
// Place appends an [Op] that places a file in container path [TmpfileOp.Path] containing [TmpfileOp.Data].
|
||||
func (f *Ops) Place(name string, data []byte) *Ops { *f = append(*f, &TmpfileOp{name, data}); return f }
|
||||
|
||||
// PlaceP is like Place but writes the address of [TmpfileOp.Data] to the pointer dataP points to.
|
||||
func (f *Ops) PlaceP(name string, dataP **[]byte) *Ops {
|
||||
t := &TmpfileOp{Path: name}
|
||||
*dataP = &t.Data
|
||||
|
||||
*f = append(*f, t)
|
||||
return f
|
||||
}
|
||||
|
||||
type TmpfileOp struct {
|
||||
Path string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func (t *TmpfileOp) early(*Params) error { return nil }
|
||||
func (t *TmpfileOp) apply(params *Params) error {
|
||||
if !path.IsAbs(t.Path) {
|
||||
return msg.WrapErr(EBADE, fmt.Sprintf("path %q is not absolute", t.Path))
|
||||
}
|
||||
|
||||
var tmpPath string
|
||||
if f, err := os.CreateTemp("/", "tmp.*"); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else if _, err = f.Write(t.Data); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
"cannot write to intermediate file:")
|
||||
} else if err = f.Close(); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
"cannot close intermediate file:")
|
||||
} else {
|
||||
tmpPath = f.Name()
|
||||
}
|
||||
|
||||
target := toSysroot(t.Path)
|
||||
if err := ensureFile(target, 0444, params.ParentPerm); err != nil {
|
||||
return err
|
||||
} else if err = hostProc.bindMount(
|
||||
tmpPath,
|
||||
target,
|
||||
MS_RDONLY|MS_NODEV,
|
||||
false,
|
||||
); err != nil {
|
||||
return err
|
||||
} else if err = os.Remove(tmpPath); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *TmpfileOp) Is(op Op) bool {
|
||||
vt, ok := op.(*TmpfileOp)
|
||||
return ok && t.Path == vt.Path && slices.Equal(t.Data, vt.Data)
|
||||
}
|
||||
func (*TmpfileOp) prefix() string { return "placing" }
|
||||
func (t *TmpfileOp) String() string {
|
||||
return fmt.Sprintf("tmpfile %q (%d bytes)", t.Path, len(t.Data))
|
||||
}
|
||||
|
||||
func init() { gob.Register(new(AutoEtcOp)) }
|
||||
|
||||
// Etc appends an [Op] that expands host /etc into a toplevel symlink mirror with /etc semantics.
|
||||
// This is not a generic setup op. It is implemented here to reduce ipc overhead.
|
||||
func (f *Ops) Etc(host, prefix string) *Ops {
|
||||
e := &AutoEtcOp{prefix}
|
||||
f.Mkdir("/etc", 0755)
|
||||
f.Bind(host, e.hostPath(), 0)
|
||||
*f = append(*f, e)
|
||||
return f
|
||||
}
|
||||
|
||||
type AutoEtcOp struct{ Prefix string }
|
||||
|
||||
func (e *AutoEtcOp) early(*Params) error { return nil }
|
||||
func (e *AutoEtcOp) apply(*Params) error {
|
||||
const target = sysrootPath + "/etc/"
|
||||
rel := e.hostRel() + "/"
|
||||
|
||||
if err := os.MkdirAll(target, 0755); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
if d, err := os.ReadDir(toSysroot(e.hostPath())); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else {
|
||||
for _, ent := range d {
|
||||
n := ent.Name()
|
||||
switch n {
|
||||
case ".host":
|
||||
|
||||
case "passwd":
|
||||
case "group":
|
||||
|
||||
case "mtab":
|
||||
if err = os.Symlink("/proc/mounts", target+n); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
|
||||
default:
|
||||
if err = os.Symlink(rel+n, target+n); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func (e *AutoEtcOp) hostPath() string { return "/etc/" + e.hostRel() }
|
||||
func (e *AutoEtcOp) hostRel() string { return ".host/" + e.Prefix }
|
||||
|
||||
func (e *AutoEtcOp) Is(op Op) bool {
|
||||
ve, ok := op.(*AutoEtcOp)
|
||||
return ok && ((e == nil && ve == nil) || (e != nil && ve != nil && *e == *ve))
|
||||
}
|
||||
func (*AutoEtcOp) prefix() string { return "setting up" }
|
||||
func (e *AutoEtcOp) String() string { return fmt.Sprintf("auto etc %s", e.Prefix) }
|
||||
26
container/output.go
Normal file
26
container/output.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package container
|
||||
|
||||
var msg Msg = new(DefaultMsg)
|
||||
|
||||
func GetOutput() Msg { return msg }
|
||||
func SetOutput(v Msg) {
|
||||
if v == nil {
|
||||
msg = new(DefaultMsg)
|
||||
} else {
|
||||
msg = v
|
||||
}
|
||||
}
|
||||
|
||||
func wrapErrSuffix(err error, a ...any) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return msg.WrapErr(err, append(a, err)...)
|
||||
}
|
||||
|
||||
func wrapErrSelf(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return msg.WrapErr(err, err.Error())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package proc
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
@@ -12,7 +12,7 @@ var (
|
||||
ErrInvalid = errors.New("bad file descriptor")
|
||||
)
|
||||
|
||||
// Setup appends the read end of a pipe for payload transmission and returns its fd.
|
||||
// Setup appends the read end of a pipe for setup params transmission and returns its fd.
|
||||
func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) {
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
return -1, nil, err
|
||||
@@ -23,9 +23,8 @@ func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Receive retrieves payload pipe fd from the environment,
|
||||
// receives its payload and returns the Close method of the pipe.
|
||||
func Receive(key string, e any) (func() error, error) {
|
||||
// Receive retrieves setup fd from the environment and receives params.
|
||||
func Receive(key string, e any, v **os.File) (func() error, error) {
|
||||
var setup *os.File
|
||||
|
||||
if s, ok := os.LookupEnv(key); !ok {
|
||||
@@ -38,8 +37,11 @@ func Receive(key string, e any) (func() error, error) {
|
||||
if setup == nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if v != nil {
|
||||
*v = setup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return func() error { return setup.Close() }, gob.NewDecoder(setup).Decode(e)
|
||||
return setup.Close, gob.NewDecoder(setup).Decode(e)
|
||||
}
|
||||
94
container/path.go
Normal file
94
container/path.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"hakurei.app/container/vfs"
|
||||
)
|
||||
|
||||
const (
|
||||
hostPath = "/" + hostDir
|
||||
hostDir = "host"
|
||||
sysrootPath = "/" + sysrootDir
|
||||
sysrootDir = "sysroot"
|
||||
)
|
||||
|
||||
func toSysroot(name string) string {
|
||||
name = strings.TrimLeftFunc(name, func(r rune) bool { return r == '/' })
|
||||
return path.Join(sysrootPath, name)
|
||||
}
|
||||
|
||||
func toHost(name string) string {
|
||||
name = strings.TrimLeftFunc(name, func(r rune) bool { return r == '/' })
|
||||
return path.Join(hostPath, name)
|
||||
}
|
||||
|
||||
func createFile(name string, perm, pperm os.FileMode, content []byte) error {
|
||||
if err := os.MkdirAll(path.Dir(name), pperm); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
f, err := os.OpenFile(name, syscall.O_CREAT|syscall.O_EXCL|syscall.O_WRONLY, perm)
|
||||
if err != nil {
|
||||
return wrapErrSelf(err)
|
||||
}
|
||||
if content != nil {
|
||||
_, err = f.Write(content)
|
||||
if err != nil {
|
||||
err = wrapErrSelf(err)
|
||||
}
|
||||
}
|
||||
return errors.Join(f.Close(), err)
|
||||
}
|
||||
|
||||
func ensureFile(name string, perm, pperm os.FileMode) error {
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return createFile(name, perm, pperm, nil)
|
||||
}
|
||||
|
||||
if mode := fi.Mode(); mode&fs.ModeDir != 0 || mode&fs.ModeSymlink != 0 {
|
||||
err = msg.WrapErr(syscall.EISDIR,
|
||||
fmt.Sprintf("path %q is a directory", name))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var hostProc = newProcPats(hostPath)
|
||||
|
||||
func newProcPats(prefix string) *procPaths {
|
||||
return &procPaths{prefix + "/proc", prefix + "/proc/self"}
|
||||
}
|
||||
|
||||
type procPaths struct {
|
||||
prefix string
|
||||
self string
|
||||
}
|
||||
|
||||
func (p *procPaths) stdout() string { return p.self + "/fd/1" }
|
||||
func (p *procPaths) fd(fd int) string { return p.self + "/fd/" + strconv.Itoa(fd) }
|
||||
func (p *procPaths) mountinfo(f func(d *vfs.MountInfoDecoder) error) error {
|
||||
if r, err := os.Open(p.self + "/mountinfo"); err != nil {
|
||||
return wrapErrSelf(err)
|
||||
} else {
|
||||
d := vfs.NewMountInfoDecoder(r)
|
||||
err0 := f(d)
|
||||
if err = r.Close(); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
"cannot close mountinfo:")
|
||||
} else if err = d.Err(); err != nil {
|
||||
return wrapErrSuffix(err,
|
||||
"cannot parse mountinfo:")
|
||||
}
|
||||
return err0
|
||||
}
|
||||
}
|
||||
24
container/seccomp/hash_amd64_test.go
Normal file
24
container/seccomp/hash_amd64_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package seccomp_test
|
||||
|
||||
import . "hakurei.app/container/seccomp"
|
||||
|
||||
var bpfExpected = bpfLookup{
|
||||
{AllowMultiarch | AllowCAN |
|
||||
AllowBluetooth, PresetExt |
|
||||
PresetDenyNS | PresetDenyTTY | PresetDenyDevel |
|
||||
PresetLinux32}: toHash(
|
||||
"e99dd345e195413473d3cbee07b4ed57b908bfa89ea2072fe93482847f50b5b758da17e74ca2bbc00813de49a2b9bf834c024ed48850be69b68a9a4c5f53a9db"),
|
||||
|
||||
{0, 0}: toHash(
|
||||
"95ec69d017733e072160e0da80fdebecdf27ae8166f5e2a731270c98ea2d2946cb5231029063668af215879155da21aca79b070e04c0ee9acdf58f55cfa815a5"),
|
||||
{0, PresetExt}: toHash(
|
||||
"dc7f2e1c5e829b79ebb7efc759150f54a83a75c8df6fee4dce5dadc4736c585d4deebfeb3c7969af3a077e90b77bb4741db05d90997c8659b95891206ac9952d"),
|
||||
{0, PresetStrict}: toHash(
|
||||
"e880298df2bd6751d0040fc21bc0ed4c00f95dc0d7ba506c244d8b8cf6866dba8ef4a33296f287b66cccc1d78e97026597f84cc7dec1573e148960fbd35cd735"),
|
||||
{0, PresetDenyNS | PresetDenyTTY | PresetDenyDevel}: toHash(
|
||||
"39871b93ffafc8b979fcedc0b0c37b9e03922f5b02748dc5c3c17c92527f6e022ede1f48bff59246ea452c0d1de54827808b1a6f84f32bbde1aa02ae30eedcfa"),
|
||||
{0, PresetExt | PresetDenyDevel}: toHash(
|
||||
"c698b081ff957afe17a6d94374537d37f2a63f6f9dd75da7546542407a9e32476ebda3312ba7785d7f618542bcfaf27ca27dcc2dddba852069d28bcfe8cad39a"),
|
||||
{0, PresetExt | PresetDenyNS | PresetDenyDevel}: toHash(
|
||||
"0b76007476c1c9e25dbf674c29fdf609a1656a70063e49327654e1b5360ad3da06e1a3e32bf80e961c5516ad83d4b9e7e9bde876a93797e27627d2555c25858b"),
|
||||
}
|
||||
24
container/seccomp/hash_arm64_test.go
Normal file
24
container/seccomp/hash_arm64_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package seccomp_test
|
||||
|
||||
import . "hakurei.app/container/seccomp"
|
||||
|
||||
var bpfExpected = bpfLookup{
|
||||
{AllowMultiarch | AllowCAN |
|
||||
AllowBluetooth, PresetExt |
|
||||
PresetDenyNS | PresetDenyTTY | PresetDenyDevel |
|
||||
PresetLinux32}: toHash(
|
||||
"1431c013f2ddac3adae577821cb5d351b1514e7c754d62346ddffd31f46ea02fb368e46e3f8104f81019617e721fe687ddd83f1e79580622ccc991da12622170"),
|
||||
|
||||
{0, 0}: toHash(
|
||||
"450c21210dbf124dfa7ae56d0130f9c2e24b26f5bce8795ee75766c75850438ff9e7d91c5e73d63bbe51a5d4b06c2a0791c4de2903b2b9805f16265318183235"),
|
||||
{0, PresetExt}: toHash(
|
||||
"d971d0f2d30f54ac920fc6d84df2be279e9fd28cf2d48be775d7fdbd790b750e1369401cd3bb8bcf9ba3adb91874fe9792d9e3f62209b8ee59c9fdd2ddd10c7b"),
|
||||
{0, PresetStrict}: toHash(
|
||||
"79318538a3dc851314b6bd96f10d5861acb2aa7e13cb8de0619d0f6a76709d67f01ef3fd67e195862b02f9711e5b769bc4d1eb4fc0dfc41a723c89c968a93297"),
|
||||
{0, PresetDenyNS | PresetDenyTTY | PresetDenyDevel}: toHash(
|
||||
"228286c2f5df8e44463be0a57b91977b7f38b63b09e5d98dfabe5c61545b8f9ac3e5ea3d86df55d7edf2ce61875f0a5a85c0ab82800bef178c42533e8bdc9a6c"),
|
||||
{0, PresetExt | PresetDenyDevel}: toHash(
|
||||
"433ce9b911282d6dcc8029319fb79b816b60d5a795ec8fc94344dd027614d68f023166a91bb881faaeeedd26e3d89474e141e5a69a97e93b8984ca8f14999980"),
|
||||
{0, PresetExt | PresetDenyNS | PresetDenyDevel}: toHash(
|
||||
"cf1f4dc87436ba8ec95d268b663a6397bb0b4a5ac64d8557e6cc529d8b0f6f65dad3a92b62ed29d85eee9c6dde1267757a4d0f86032e8a45ca1bceadfa34cf5e"),
|
||||
}
|
||||
28
container/seccomp/hash_test.go
Normal file
28
container/seccomp/hash_test.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package seccomp_test
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
)
|
||||
|
||||
type (
|
||||
bpfPreset = struct {
|
||||
seccomp.ExportFlag
|
||||
seccomp.FilterPreset
|
||||
}
|
||||
bpfLookup map[bpfPreset][]byte
|
||||
)
|
||||
|
||||
func toHash(s string) []byte {
|
||||
if len(s) != 128 {
|
||||
panic("bad sha512 string length")
|
||||
}
|
||||
if v, err := hex.DecodeString(s); err != nil {
|
||||
panic(err.Error())
|
||||
} else if len(v) != 64 {
|
||||
panic("unreachable")
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
130
container/seccomp/libseccomp-helper.c
Normal file
130
container/seccomp/libseccomp-helper.c
Normal file
@@ -0,0 +1,130 @@
|
||||
#ifndef _GNU_SOURCE
|
||||
#define _GNU_SOURCE /* CLONE_NEWUSER */
|
||||
#endif
|
||||
|
||||
#include "libseccomp-helper.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#define LEN(arr) (sizeof(arr) / sizeof((arr)[0]))
|
||||
|
||||
int32_t hakurei_export_filter(int *ret_p, int fd, uint32_t arch,
|
||||
uint32_t multiarch,
|
||||
struct hakurei_syscall_rule *rules,
|
||||
size_t rules_sz, hakurei_export_flag flags) {
|
||||
int i;
|
||||
int last_allowed_family;
|
||||
int disallowed;
|
||||
struct hakurei_syscall_rule *rule;
|
||||
|
||||
int32_t res = 0; /* refer to resPrefix for message */
|
||||
|
||||
/* Blocklist all but unix, inet, inet6 and netlink */
|
||||
struct {
|
||||
int family;
|
||||
hakurei_export_flag flags_mask;
|
||||
} socket_family_allowlist[] = {
|
||||
/* NOTE: Keep in numerical order */
|
||||
{AF_UNSPEC, 0},
|
||||
{AF_LOCAL, 0},
|
||||
{AF_INET, 0},
|
||||
{AF_INET6, 0},
|
||||
{AF_NETLINK, 0},
|
||||
{AF_CAN, HAKUREI_EXPORT_CAN},
|
||||
{AF_BLUETOOTH, HAKUREI_EXPORT_BLUETOOTH},
|
||||
};
|
||||
|
||||
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
|
||||
if (ctx == NULL) {
|
||||
res = 1;
|
||||
goto out;
|
||||
} else
|
||||
errno = 0;
|
||||
|
||||
/* We only really need to handle arches on multiarch systems.
|
||||
* If only one arch is supported the default is fine */
|
||||
if (arch != 0) {
|
||||
/* This *adds* the target arch, instead of replacing the
|
||||
* native one. This is not ideal, because we'd like to only
|
||||
* allow the target arch, but we can't really disallow the
|
||||
* native arch at this point, because then bubblewrap
|
||||
* couldn't continue running. */
|
||||
*ret_p = seccomp_arch_add(ctx, arch);
|
||||
if (*ret_p < 0 && *ret_p != -EEXIST) {
|
||||
res = 2;
|
||||
goto out;
|
||||
}
|
||||
|
||||
if (flags & HAKUREI_EXPORT_MULTIARCH && multiarch != 0) {
|
||||
*ret_p = seccomp_arch_add(ctx, multiarch);
|
||||
if (*ret_p < 0 && *ret_p != -EEXIST) {
|
||||
res = 3;
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < rules_sz; i++) {
|
||||
rule = &rules[i];
|
||||
assert(rule->m_errno == EPERM || rule->m_errno == ENOSYS);
|
||||
|
||||
if (rule->arg)
|
||||
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno),
|
||||
rule->syscall, 1, *rule->arg);
|
||||
else
|
||||
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno),
|
||||
rule->syscall, 0);
|
||||
|
||||
if (*ret_p == -EFAULT) {
|
||||
res = 4;
|
||||
goto out;
|
||||
} else if (*ret_p < 0) {
|
||||
res = 5;
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
|
||||
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
|
||||
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
|
||||
* something else: https://github.com/seccomp/libseccomp/issues/8 */
|
||||
last_allowed_family = -1;
|
||||
for (i = 0; i < LEN(socket_family_allowlist); i++) {
|
||||
if (socket_family_allowlist[i].flags_mask != 0 &&
|
||||
(socket_family_allowlist[i].flags_mask & flags) !=
|
||||
socket_family_allowlist[i].flags_mask)
|
||||
continue;
|
||||
|
||||
for (disallowed = last_allowed_family + 1;
|
||||
disallowed < socket_family_allowlist[i].family; disallowed++) {
|
||||
/* Blocklist the in-between valid families */
|
||||
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT),
|
||||
SCMP_SYS(socket), 1,
|
||||
SCMP_A0(SCMP_CMP_EQ, disallowed));
|
||||
}
|
||||
last_allowed_family = socket_family_allowlist[i].family;
|
||||
}
|
||||
/* Blocklist the rest */
|
||||
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT), SCMP_SYS(socket), 1,
|
||||
SCMP_A0(SCMP_CMP_GE, last_allowed_family + 1));
|
||||
|
||||
if (fd < 0) {
|
||||
*ret_p = seccomp_load(ctx);
|
||||
if (*ret_p != 0) {
|
||||
res = 7;
|
||||
goto out;
|
||||
}
|
||||
} else {
|
||||
*ret_p = seccomp_export_bpf(ctx, fd);
|
||||
if (*ret_p != 0) {
|
||||
res = 6;
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
|
||||
out:
|
||||
if (ctx)
|
||||
seccomp_release(ctx);
|
||||
|
||||
return res;
|
||||
}
|
||||
24
container/seccomp/libseccomp-helper.h
Normal file
24
container/seccomp/libseccomp-helper.h
Normal file
@@ -0,0 +1,24 @@
|
||||
#include <seccomp.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#if (SCMP_VER_MAJOR < 2) || (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5) || \
|
||||
(SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR == 5 && SCMP_VER_MICRO < 1)
|
||||
#error This package requires libseccomp >= v2.5.1
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
HAKUREI_EXPORT_MULTIARCH = 1 << 0,
|
||||
HAKUREI_EXPORT_CAN = 1 << 1,
|
||||
HAKUREI_EXPORT_BLUETOOTH = 1 << 2,
|
||||
} hakurei_export_flag;
|
||||
|
||||
struct hakurei_syscall_rule {
|
||||
int syscall;
|
||||
int m_errno;
|
||||
struct scmp_arg_cmp *arg;
|
||||
};
|
||||
|
||||
int32_t hakurei_export_filter(int *ret_p, int fd, uint32_t arch,
|
||||
uint32_t multiarch,
|
||||
struct hakurei_syscall_rule *rules,
|
||||
size_t rules_sz, hakurei_export_flag flags);
|
||||
194
container/seccomp/libseccomp.go
Normal file
194
container/seccomp/libseccomp.go
Normal file
@@ -0,0 +1,194 @@
|
||||
package seccomp
|
||||
|
||||
/*
|
||||
#cgo linux pkg-config: --static libseccomp
|
||||
|
||||
#include <libseccomp-helper.h>
|
||||
#include <sys/personality.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
PER_LINUX = C.PER_LINUX
|
||||
PER_LINUX32 = C.PER_LINUX32
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRules = errors.New("invalid native rules slice")
|
||||
)
|
||||
|
||||
// LibraryError represents a libseccomp error.
|
||||
type LibraryError struct {
|
||||
Prefix string
|
||||
Seccomp syscall.Errno
|
||||
Errno error
|
||||
}
|
||||
|
||||
func (e *LibraryError) Error() string {
|
||||
if e.Seccomp == 0 {
|
||||
if e.Errno == nil {
|
||||
panic("invalid libseccomp error")
|
||||
}
|
||||
return fmt.Sprintf("%s: %s", e.Prefix, e.Errno)
|
||||
}
|
||||
if e.Errno == nil {
|
||||
return fmt.Sprintf("%s: %s", e.Prefix, e.Seccomp)
|
||||
}
|
||||
return fmt.Sprintf("%s: %s (%s)", e.Prefix, e.Seccomp, e.Errno)
|
||||
}
|
||||
|
||||
func (e *LibraryError) Is(err error) bool {
|
||||
if e == nil {
|
||||
return err == nil
|
||||
}
|
||||
if ef, ok := err.(*LibraryError); ok {
|
||||
return *e == *ef
|
||||
}
|
||||
return (e.Seccomp != 0 && errors.Is(err, e.Seccomp)) ||
|
||||
(e.Errno != nil && errors.Is(err, e.Errno))
|
||||
}
|
||||
|
||||
type (
|
||||
ScmpSyscall = C.int
|
||||
ScmpErrno = C.int
|
||||
)
|
||||
|
||||
// A NativeRule specifies an arch-specific action taken by seccomp under certain conditions.
|
||||
type NativeRule struct {
|
||||
// Syscall is the arch-dependent syscall number to act against.
|
||||
Syscall ScmpSyscall
|
||||
// Errno is the errno value to return when the condition is satisfied.
|
||||
Errno ScmpErrno
|
||||
// Arg is the optional struct scmp_arg_cmp passed to libseccomp.
|
||||
Arg *ScmpArgCmp
|
||||
}
|
||||
|
||||
type ExportFlag = C.hakurei_export_flag
|
||||
|
||||
const (
|
||||
// AllowMultiarch allows multiarch/emulation.
|
||||
AllowMultiarch ExportFlag = C.HAKUREI_EXPORT_MULTIARCH
|
||||
// AllowCAN allows AF_CAN.
|
||||
AllowCAN ExportFlag = C.HAKUREI_EXPORT_CAN
|
||||
// AllowBluetooth allows AF_BLUETOOTH.
|
||||
AllowBluetooth ExportFlag = C.HAKUREI_EXPORT_BLUETOOTH
|
||||
)
|
||||
|
||||
var resPrefix = [...]string{
|
||||
0: "",
|
||||
1: "seccomp_init failed",
|
||||
2: "seccomp_arch_add failed",
|
||||
3: "seccomp_arch_add failed (multiarch)",
|
||||
4: "internal libseccomp failure",
|
||||
5: "seccomp_rule_add failed",
|
||||
6: "seccomp_export_bpf failed",
|
||||
7: "seccomp_load failed",
|
||||
}
|
||||
|
||||
// Export streams filter contents to fd, or installs it to the current process if fd < 0.
|
||||
func Export(fd int, rules []NativeRule, flags ExportFlag) error {
|
||||
if len(rules) == 0 {
|
||||
return ErrInvalidRules
|
||||
}
|
||||
|
||||
var (
|
||||
arch C.uint32_t = 0
|
||||
multiarch C.uint32_t = 0
|
||||
)
|
||||
switch runtime.GOARCH {
|
||||
case "386":
|
||||
arch = C.SCMP_ARCH_X86
|
||||
case "amd64":
|
||||
arch = C.SCMP_ARCH_X86_64
|
||||
multiarch = C.SCMP_ARCH_X86
|
||||
case "arm":
|
||||
arch = C.SCMP_ARCH_ARM
|
||||
case "arm64":
|
||||
arch = C.SCMP_ARCH_AARCH64
|
||||
multiarch = C.SCMP_ARCH_ARM
|
||||
}
|
||||
|
||||
var ret C.int
|
||||
|
||||
rulesPinner := new(runtime.Pinner)
|
||||
for i := range rules {
|
||||
rule := &rules[i]
|
||||
rulesPinner.Pin(rule)
|
||||
if rule.Arg != nil {
|
||||
rulesPinner.Pin(rule.Arg)
|
||||
}
|
||||
}
|
||||
res, err := C.hakurei_export_filter(
|
||||
&ret, C.int(fd),
|
||||
arch, multiarch,
|
||||
(*C.struct_hakurei_syscall_rule)(unsafe.Pointer(&rules[0])),
|
||||
C.size_t(len(rules)),
|
||||
flags,
|
||||
)
|
||||
rulesPinner.Unpin()
|
||||
|
||||
if prefix := resPrefix[res]; prefix != "" {
|
||||
return &LibraryError{
|
||||
prefix,
|
||||
-syscall.Errno(ret),
|
||||
err,
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ScmpCompare is the equivalent of scmp_compare;
|
||||
// Comparison operators
|
||||
type ScmpCompare = C.enum_scmp_compare
|
||||
|
||||
const (
|
||||
_SCMP_CMP_MIN = C._SCMP_CMP_MIN
|
||||
|
||||
// not equal
|
||||
SCMP_CMP_NE = C.SCMP_CMP_NE
|
||||
// less than
|
||||
SCMP_CMP_LT = C.SCMP_CMP_LT
|
||||
// less than or equal
|
||||
SCMP_CMP_LE = C.SCMP_CMP_LE
|
||||
// equal
|
||||
SCMP_CMP_EQ = C.SCMP_CMP_EQ
|
||||
// greater than or equal
|
||||
SCMP_CMP_GE = C.SCMP_CMP_GE
|
||||
// greater than
|
||||
SCMP_CMP_GT = C.SCMP_CMP_GT
|
||||
// masked equality
|
||||
SCMP_CMP_MASKED_EQ = C.SCMP_CMP_MASKED_EQ
|
||||
|
||||
_SCMP_CMP_MAX = C._SCMP_CMP_MAX
|
||||
)
|
||||
|
||||
// ScmpDatum is the equivalent of scmp_datum_t;
|
||||
// Argument datum
|
||||
type ScmpDatum uint64
|
||||
|
||||
// ScmpArgCmp is the equivalent of struct scmp_arg_cmp;
|
||||
// Argument / Value comparison definition
|
||||
type ScmpArgCmp struct {
|
||||
// argument number, starting at 0
|
||||
Arg C.uint
|
||||
// the comparison op, e.g. SCMP_CMP_*
|
||||
Op ScmpCompare
|
||||
|
||||
DatumA, DatumB ScmpDatum
|
||||
}
|
||||
|
||||
// only used for testing
|
||||
func syscallResolveName(s string) (trap int) {
|
||||
v := C.CString(s)
|
||||
trap = int(C.seccomp_syscall_resolve_name(v))
|
||||
C.free(unsafe.Pointer(v))
|
||||
|
||||
return
|
||||
}
|
||||
94
container/seccomp/libseccomp_test.go
Normal file
94
container/seccomp/libseccomp_test.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package seccomp_test
|
||||
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"errors"
|
||||
"io"
|
||||
"slices"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
. "hakurei.app/container/seccomp"
|
||||
)
|
||||
|
||||
func TestExport(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
flags ExportFlag
|
||||
presets FilterPreset
|
||||
wantErr bool
|
||||
}{
|
||||
{"everything", AllowMultiarch | AllowCAN |
|
||||
AllowBluetooth, PresetExt |
|
||||
PresetDenyNS | PresetDenyTTY | PresetDenyDevel |
|
||||
PresetLinux32, false},
|
||||
|
||||
{"compat", 0, 0, false},
|
||||
{"base", 0, PresetExt, false},
|
||||
{"strict", 0, PresetStrict, false},
|
||||
{"strict compat", 0, PresetDenyNS | PresetDenyTTY | PresetDenyDevel, false},
|
||||
{"hakurei default", 0, PresetExt | PresetDenyDevel, false},
|
||||
{"hakurei tty", 0, PresetExt | PresetDenyNS | PresetDenyDevel, false},
|
||||
}
|
||||
|
||||
buf := make([]byte, 8)
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
e := New(Preset(tc.presets, tc.flags), tc.flags)
|
||||
want := bpfExpected[bpfPreset{tc.flags, tc.presets}]
|
||||
digest := sha512.New()
|
||||
|
||||
if _, err := io.CopyBuffer(digest, e, buf); (err != nil) != tc.wantErr {
|
||||
t.Errorf("Exporter: error = %v, wantErr %v", err, tc.wantErr)
|
||||
return
|
||||
}
|
||||
if err := e.Close(); err != nil {
|
||||
t.Errorf("Close: error = %v", err)
|
||||
}
|
||||
if got := digest.Sum(nil); !slices.Equal(got, want) {
|
||||
t.Fatalf("Export() hash = %x, want %x",
|
||||
got, want)
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("close without use", func(t *testing.T) {
|
||||
e := New(Preset(0, 0), 0)
|
||||
if err := e.Close(); !errors.Is(err, syscall.EINVAL) {
|
||||
t.Errorf("Close: error = %v", err)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("close partial read", func(t *testing.T) {
|
||||
e := New(Preset(0, 0), 0)
|
||||
if _, err := e.Read(nil); err != nil {
|
||||
t.Errorf("Read: error = %v", err)
|
||||
return
|
||||
}
|
||||
// the underlying implementation uses buffered io, so the outcome of this is nondeterministic;
|
||||
// that is not harmful however, so both outcomes are checked for here
|
||||
if err := e.Close(); err != nil &&
|
||||
(!errors.Is(err, syscall.ECANCELED) || !errors.Is(err, syscall.EBADF)) {
|
||||
t.Errorf("Close: error = %v", err)
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkExport(b *testing.B) {
|
||||
buf := make([]byte, 8)
|
||||
for b.Loop() {
|
||||
e := New(
|
||||
Preset(PresetExt|PresetDenyNS|PresetDenyTTY|PresetDenyDevel|PresetLinux32,
|
||||
AllowMultiarch|AllowCAN|AllowBluetooth),
|
||||
AllowMultiarch|AllowCAN|AllowBluetooth)
|
||||
if _, err := io.CopyBuffer(io.Discard, e, buf); err != nil {
|
||||
b.Fatalf("cannot export: %v", err)
|
||||
}
|
||||
if err := e.Close(); err != nil {
|
||||
b.Fatalf("cannot close exporter: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
89
container/seccomp/mksysnum_linux.pl
Executable file
89
container/seccomp/mksysnum_linux.pl
Executable file
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env perl
|
||||
# Copyright 2009 The Go Authors. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style
|
||||
# license that can be found in the LICENSE file.
|
||||
|
||||
use strict;
|
||||
use POSIX ();
|
||||
|
||||
my $command = "mksysnum_linux.pl ". join(' ', @ARGV);
|
||||
my $uname_arch = (POSIX::uname)[4];
|
||||
my %syscall_cutoff_arch = (
|
||||
"x86_64" => 302,
|
||||
"aarch64" => 281,
|
||||
);
|
||||
|
||||
print <<EOF;
|
||||
// $command
|
||||
// Code generated by the command above; DO NOT EDIT.
|
||||
|
||||
package seccomp
|
||||
|
||||
import . "syscall"
|
||||
|
||||
var syscallNum = map[string]int{
|
||||
EOF
|
||||
|
||||
my $offset = 0;
|
||||
my $state = -1;
|
||||
|
||||
sub fmt {
|
||||
my ($name, $num) = @_;
|
||||
if($num > 999){
|
||||
# ignore deprecated syscalls that are no longer implemented
|
||||
# https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716
|
||||
return;
|
||||
}
|
||||
(my $name_upper = $name) =~ y/a-z/A-Z/;
|
||||
$num = $num + $offset;
|
||||
if($num > $syscall_cutoff_arch{$uname_arch}){ # not wired in Go standard library
|
||||
if($state < 0){
|
||||
print " \"$name\": SYS_$name_upper,\n";
|
||||
}
|
||||
else{
|
||||
print " SYS_$name_upper = $num;\n";
|
||||
}
|
||||
}
|
||||
elsif($state < 0){
|
||||
print " \"$name\": SYS_$name_upper,\n";
|
||||
}
|
||||
else{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
GENERATE:
|
||||
|
||||
my $prev;
|
||||
open(GCC, "gcc -E -dD $ARGV[0] |") || die "can't run gcc";
|
||||
while(<GCC>){
|
||||
if(/^#define __NR_Linux\s+([0-9]+)/){
|
||||
# mips/mips64: extract offset
|
||||
$offset = $1;
|
||||
}
|
||||
elsif(/^#define __NR_syscalls\s+/) {
|
||||
# ignore redefinitions of __NR_syscalls
|
||||
}
|
||||
elsif(/^#define __NR_(\w+)\s+([0-9]+)/){
|
||||
$prev = $2;
|
||||
fmt($1, $2);
|
||||
}
|
||||
elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){
|
||||
$prev = $2;
|
||||
fmt($1, $2);
|
||||
}
|
||||
elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){
|
||||
fmt($1, $prev+$2)
|
||||
}
|
||||
elsif(/^#define __NR_(\w+)\s+\(__NR_Linux \+ ([0-9]+)/){
|
||||
fmt($1, $2);
|
||||
}
|
||||
}
|
||||
|
||||
if($state < 0){
|
||||
$state = $state + 1;
|
||||
print "}\n\nconst (\n";
|
||||
goto GENERATE;
|
||||
}
|
||||
|
||||
print ")";
|
||||
229
container/seccomp/presets.go
Normal file
229
container/seccomp/presets.go
Normal file
@@ -0,0 +1,229 @@
|
||||
package seccomp
|
||||
|
||||
/* flatpak commit 4c3bf179e2e4a2a298cd1db1d045adaf3f564532 */
|
||||
|
||||
import (
|
||||
. "syscall"
|
||||
)
|
||||
|
||||
type FilterPreset int
|
||||
|
||||
const (
|
||||
// PresetExt are project-specific extensions.
|
||||
PresetExt FilterPreset = 1 << iota
|
||||
// PresetDenyNS denies namespace setup syscalls.
|
||||
PresetDenyNS
|
||||
// PresetDenyTTY denies faking input.
|
||||
PresetDenyTTY
|
||||
// PresetDenyDevel denies development-related syscalls.
|
||||
PresetDenyDevel
|
||||
// PresetLinux32 sets PER_LINUX32.
|
||||
PresetLinux32
|
||||
)
|
||||
|
||||
func Preset(presets FilterPreset, flags ExportFlag) (rules []NativeRule) {
|
||||
allowedPersonality := PER_LINUX
|
||||
if presets&PresetLinux32 != 0 {
|
||||
allowedPersonality = PER_LINUX32
|
||||
}
|
||||
presetDevelFinal := presetDevel(ScmpDatum(allowedPersonality))
|
||||
|
||||
l := len(presetCommon)
|
||||
if presets&PresetDenyNS != 0 {
|
||||
l += len(presetNamespace)
|
||||
}
|
||||
if presets&PresetDenyTTY != 0 {
|
||||
l += len(presetTTY)
|
||||
}
|
||||
if presets&PresetDenyDevel != 0 {
|
||||
l += len(presetDevelFinal)
|
||||
}
|
||||
if flags&AllowMultiarch == 0 {
|
||||
l += len(presetEmu)
|
||||
}
|
||||
if presets&PresetExt != 0 {
|
||||
l += len(presetCommonExt)
|
||||
if presets&PresetDenyNS != 0 {
|
||||
l += len(presetNamespaceExt)
|
||||
}
|
||||
if flags&AllowMultiarch == 0 {
|
||||
l += len(presetEmuExt)
|
||||
}
|
||||
}
|
||||
|
||||
rules = make([]NativeRule, 0, l)
|
||||
rules = append(rules, presetCommon...)
|
||||
if presets&PresetDenyNS != 0 {
|
||||
rules = append(rules, presetNamespace...)
|
||||
}
|
||||
if presets&PresetDenyTTY != 0 {
|
||||
rules = append(rules, presetTTY...)
|
||||
}
|
||||
if presets&PresetDenyDevel != 0 {
|
||||
rules = append(rules, presetDevelFinal...)
|
||||
}
|
||||
if flags&AllowMultiarch == 0 {
|
||||
rules = append(rules, presetEmu...)
|
||||
}
|
||||
if presets&PresetExt != 0 {
|
||||
rules = append(rules, presetCommonExt...)
|
||||
if presets&PresetDenyNS != 0 {
|
||||
rules = append(rules, presetNamespaceExt...)
|
||||
}
|
||||
if flags&AllowMultiarch == 0 {
|
||||
rules = append(rules, presetEmuExt...)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
presetCommon = []NativeRule{
|
||||
/* Block dmesg */
|
||||
{ScmpSyscall(SYS_SYSLOG), ScmpErrno(EPERM), nil},
|
||||
/* Useless old syscall */
|
||||
{ScmpSyscall(SYS_USELIB), ScmpErrno(EPERM), nil},
|
||||
/* Don't allow disabling accounting */
|
||||
{ScmpSyscall(SYS_ACCT), ScmpErrno(EPERM), nil},
|
||||
/* Don't allow reading current quota use */
|
||||
{ScmpSyscall(SYS_QUOTACTL), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* Don't allow access to the kernel keyring */
|
||||
{ScmpSyscall(SYS_ADD_KEY), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_KEYCTL), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_REQUEST_KEY), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* Scary VM/NUMA ops */
|
||||
{ScmpSyscall(SYS_MOVE_PAGES), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_MBIND), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_GET_MEMPOLICY), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SET_MEMPOLICY), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_MIGRATE_PAGES), ScmpErrno(EPERM), nil},
|
||||
}
|
||||
|
||||
/* hakurei: project-specific extensions */
|
||||
presetCommonExt = []NativeRule{
|
||||
/* system calls for changing the system clock */
|
||||
{ScmpSyscall(SYS_ADJTIMEX), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CLOCK_ADJTIME), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CLOCK_ADJTIME64), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CLOCK_SETTIME), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CLOCK_SETTIME64), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETTIMEOFDAY), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* loading and unloading of kernel modules */
|
||||
{ScmpSyscall(SYS_DELETE_MODULE), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_FINIT_MODULE), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_INIT_MODULE), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* system calls for rebooting and reboot preparation */
|
||||
{ScmpSyscall(SYS_KEXEC_FILE_LOAD), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_KEXEC_LOAD), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_REBOOT), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* system calls for enabling/disabling swap devices */
|
||||
{ScmpSyscall(SYS_SWAPOFF), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SWAPON), ScmpErrno(EPERM), nil},
|
||||
}
|
||||
|
||||
presetNamespace = []NativeRule{
|
||||
/* Don't allow subnamespace setups: */
|
||||
{ScmpSyscall(SYS_UNSHARE), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETNS), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_MOUNT), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_UMOUNT), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_UMOUNT2), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_PIVOT_ROOT), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CHROOT), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CLONE), ScmpErrno(EPERM),
|
||||
&ScmpArgCmp{cloneArg, SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER}},
|
||||
|
||||
/* seccomp can't look into clone3()'s struct clone_args to check whether
|
||||
* the flags are OK, so we have no choice but to block clone3().
|
||||
* Return ENOSYS so user-space will fall back to clone().
|
||||
* (CVE-2021-41133; see also https://github.com/moby/moby/commit/9f6b562d)
|
||||
*/
|
||||
{ScmpSyscall(SYS_CLONE3), ScmpErrno(ENOSYS), nil},
|
||||
|
||||
/* New mount manipulation APIs can also change our VFS. There's no
|
||||
* legitimate reason to do these in the sandbox, so block all of them
|
||||
* rather than thinking about which ones might be dangerous.
|
||||
* (CVE-2021-41133) */
|
||||
{ScmpSyscall(SYS_OPEN_TREE), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_MOVE_MOUNT), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_FSOPEN), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_FSCONFIG), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_FSMOUNT), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_FSPICK), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_MOUNT_SETATTR), ScmpErrno(ENOSYS), nil},
|
||||
}
|
||||
|
||||
/* hakurei: project-specific extensions */
|
||||
presetNamespaceExt = []NativeRule{
|
||||
/* changing file ownership */
|
||||
{ScmpSyscall(SYS_CHOWN), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_CHOWN32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_FCHOWN), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_FCHOWN32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_FCHOWNAT), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_LCHOWN), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_LCHOWN32), ScmpErrno(EPERM), nil},
|
||||
|
||||
/* system calls for changing user ID and group ID credentials */
|
||||
{ScmpSyscall(SYS_SETGID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETGID32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETGROUPS), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETGROUPS32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETREGID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETREGID32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETRESGID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETRESGID32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETRESUID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETRESUID32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETREUID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETREUID32), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETUID), ScmpErrno(EPERM), nil},
|
||||
{ScmpSyscall(SYS_SETUID32), ScmpErrno(EPERM), nil},
|
||||
}
|
||||
|
||||
presetTTY = []NativeRule{
|
||||
/* Don't allow faking input to the controlling tty (CVE-2017-5226) */
|
||||
{ScmpSyscall(SYS_IOCTL), ScmpErrno(EPERM),
|
||||
&ScmpArgCmp{1, SCMP_CMP_MASKED_EQ, 0xFFFFFFFF, TIOCSTI}},
|
||||
/* In the unlikely event that the controlling tty is a Linux virtual
|
||||
* console (/dev/tty2 or similar), copy/paste operations have an effect
|
||||
* similar to TIOCSTI (CVE-2023-28100) */
|
||||
{ScmpSyscall(SYS_IOCTL), ScmpErrno(EPERM),
|
||||
&ScmpArgCmp{1, SCMP_CMP_MASKED_EQ, 0xFFFFFFFF, TIOCLINUX}},
|
||||
}
|
||||
|
||||
presetEmu = []NativeRule{
|
||||
/* modify_ldt is a historic source of interesting information leaks,
|
||||
* so it's disabled as a hardening measure.
|
||||
* However, it is required to run old 16-bit applications
|
||||
* as well as some Wine patches, so it's allowed in multiarch. */
|
||||
{ScmpSyscall(SYS_MODIFY_LDT), ScmpErrno(EPERM), nil},
|
||||
}
|
||||
|
||||
/* hakurei: project-specific extensions */
|
||||
presetEmuExt = []NativeRule{
|
||||
{ScmpSyscall(SYS_SUBPAGE_PROT), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_SWITCH_ENDIAN), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_VM86), ScmpErrno(ENOSYS), nil},
|
||||
{ScmpSyscall(SYS_VM86OLD), ScmpErrno(ENOSYS), nil},
|
||||
}
|
||||
)
|
||||
|
||||
func presetDevel(allowedPersonality ScmpDatum) []NativeRule {
|
||||
return []NativeRule{
|
||||
/* Profiling operations; we expect these to be done by tools from outside
|
||||
* the sandbox. In particular perf has been the source of many CVEs. */
|
||||
{ScmpSyscall(SYS_PERF_EVENT_OPEN), ScmpErrno(EPERM), nil},
|
||||
/* Don't allow you to switch to bsd emulation or whatnot */
|
||||
{ScmpSyscall(SYS_PERSONALITY), ScmpErrno(EPERM),
|
||||
&ScmpArgCmp{0, SCMP_CMP_NE, allowedPersonality, 0}},
|
||||
|
||||
{ScmpSyscall(SYS_PTRACE), ScmpErrno(EPERM), nil},
|
||||
}
|
||||
}
|
||||
7
container/seccomp/presets_clone_backwards2.go
Normal file
7
container/seccomp/presets_clone_backwards2.go
Normal file
@@ -0,0 +1,7 @@
|
||||
//go:build s390 || s390x
|
||||
|
||||
package seccomp
|
||||
|
||||
/* Architectures with CONFIG_CLONE_BACKWARDS2: the child stack
|
||||
* and flags arguments are reversed so the flags come second */
|
||||
const cloneArg = 1
|
||||
6
container/seccomp/presets_clone_generic.go
Normal file
6
container/seccomp/presets_clone_generic.go
Normal file
@@ -0,0 +1,6 @@
|
||||
//go:build !s390 && !s390x
|
||||
|
||||
package seccomp
|
||||
|
||||
/* Normally the flags come first */
|
||||
const cloneArg = 0
|
||||
@@ -5,11 +5,18 @@ import (
|
||||
"errors"
|
||||
"syscall"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper/proc"
|
||||
"hakurei.app/helper/proc"
|
||||
)
|
||||
|
||||
const (
|
||||
PresetStrict = PresetExt | PresetDenyNS | PresetDenyTTY | PresetDenyDevel
|
||||
)
|
||||
|
||||
// New returns an inactive Encoder instance.
|
||||
func New(opts SyscallOpts) *Encoder { return &Encoder{newExporter(opts)} }
|
||||
func New(rules []NativeRule, flags ExportFlag) *Encoder { return &Encoder{newExporter(rules, flags)} }
|
||||
|
||||
// Load loads a filter into the kernel.
|
||||
func Load(rules []NativeRule, flags ExportFlag) error { return Export(-1, rules, flags) }
|
||||
|
||||
/*
|
||||
An Encoder writes a BPF program to an output stream.
|
||||
@@ -39,17 +46,20 @@ func (e *Encoder) Close() error {
|
||||
}
|
||||
|
||||
// NewFile returns an instance of exporter implementing [proc.File].
|
||||
func NewFile(opts SyscallOpts) proc.File { return &File{opts: opts} }
|
||||
func NewFile(rules []NativeRule, flags ExportFlag) proc.File {
|
||||
return &File{rules: rules, flags: flags}
|
||||
}
|
||||
|
||||
// File implements [proc.File] and provides access to the read end of exporter pipe.
|
||||
type File struct {
|
||||
opts SyscallOpts
|
||||
rules []NativeRule
|
||||
flags ExportFlag
|
||||
proc.BaseFile
|
||||
}
|
||||
|
||||
func (f *File) ErrCount() int { return 2 }
|
||||
func (f *File) Fulfill(ctx context.Context, dispatchErr func(error)) error {
|
||||
e := newExporter(f.opts)
|
||||
e := newExporter(f.rules, f.flags)
|
||||
if err := e.prepare(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// Package seccomp provides high level wrappers around libseccomp.
|
||||
package seccomp
|
||||
|
||||
import (
|
||||
@@ -7,8 +8,9 @@ import (
|
||||
)
|
||||
|
||||
type exporter struct {
|
||||
opts SyscallOpts
|
||||
r, w *os.File
|
||||
rules []NativeRule
|
||||
flags ExportFlag
|
||||
r, w *os.File
|
||||
|
||||
prepareOnce sync.Once
|
||||
prepareErr error
|
||||
@@ -27,7 +29,12 @@ func (e *exporter) prepare() error {
|
||||
}
|
||||
|
||||
ec := make(chan error, 1)
|
||||
go func(fd uintptr) { ec <- exportFilter(fd, e.opts); close(ec); _ = e.closeWrite() }(e.w.Fd())
|
||||
go func(fd uintptr) {
|
||||
ec <- Export(int(fd), e.rules, e.flags)
|
||||
close(ec)
|
||||
_ = e.closeWrite()
|
||||
runtime.KeepAlive(e.w)
|
||||
}(e.w.Fd())
|
||||
e.exportErr = ec
|
||||
runtime.SetFinalizer(e, (*exporter).closeWrite)
|
||||
})
|
||||
@@ -48,6 +55,6 @@ func (e *exporter) closeWrite() error {
|
||||
return e.closeErr
|
||||
}
|
||||
|
||||
func newExporter(opts SyscallOpts) *exporter {
|
||||
return &exporter{opts: opts}
|
||||
func newExporter(rules []NativeRule, flags ExportFlag) *exporter {
|
||||
return &exporter{rules: rules, flags: flags}
|
||||
}
|
||||
65
container/seccomp/seccomp_test.go
Normal file
65
container/seccomp/seccomp_test.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package seccomp_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container/seccomp"
|
||||
)
|
||||
|
||||
func TestLibraryError(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
sample *seccomp.LibraryError
|
||||
want string
|
||||
wantIs bool
|
||||
compare error
|
||||
}{
|
||||
{
|
||||
"full",
|
||||
&seccomp.LibraryError{Prefix: "seccomp_export_bpf failed", Seccomp: syscall.ECANCELED, Errno: syscall.EBADF},
|
||||
"seccomp_export_bpf failed: operation canceled (bad file descriptor)",
|
||||
true,
|
||||
&seccomp.LibraryError{Prefix: "seccomp_export_bpf failed", Seccomp: syscall.ECANCELED, Errno: syscall.EBADF},
|
||||
},
|
||||
{
|
||||
"errno only",
|
||||
&seccomp.LibraryError{Prefix: "seccomp_init failed", Errno: syscall.ENOMEM},
|
||||
"seccomp_init failed: cannot allocate memory",
|
||||
false,
|
||||
nil,
|
||||
},
|
||||
{
|
||||
"seccomp only",
|
||||
&seccomp.LibraryError{Prefix: "internal libseccomp failure", Seccomp: syscall.EFAULT},
|
||||
"internal libseccomp failure: bad address",
|
||||
true,
|
||||
syscall.EFAULT,
|
||||
},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if errors.Is(tc.sample, tc.compare) != tc.wantIs {
|
||||
t.Errorf("errors.Is(%#v, %#v) did not return %v",
|
||||
tc.sample, tc.compare, tc.wantIs)
|
||||
}
|
||||
|
||||
if got := tc.sample.Error(); got != tc.want {
|
||||
t.Errorf("Error: %q, want %q",
|
||||
got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("invalid", func(t *testing.T) {
|
||||
wantPanic := "invalid libseccomp error"
|
||||
defer func() {
|
||||
if r := recover(); r != wantPanic {
|
||||
t.Errorf("panic: %q, want %q", r, wantPanic)
|
||||
}
|
||||
}()
|
||||
runtime.KeepAlive(new(seccomp.LibraryError).Error())
|
||||
})
|
||||
}
|
||||
28
container/seccomp/syscall.go
Normal file
28
container/seccomp/syscall.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package seccomp
|
||||
|
||||
import "iter"
|
||||
|
||||
// Syscalls returns an iterator over all wired syscalls.
|
||||
func Syscalls() iter.Seq2[string, int] {
|
||||
return func(yield func(string, int) bool) {
|
||||
for name, num := range syscallNum {
|
||||
if !yield(name, num) {
|
||||
return
|
||||
}
|
||||
}
|
||||
for name, num := range syscallNumExtra {
|
||||
if !yield(name, num) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SyscallResolveName resolves a syscall number from its string representation.
|
||||
func SyscallResolveName(name string) (num int, ok bool) {
|
||||
if num, ok = syscallNum[name]; ok {
|
||||
return
|
||||
}
|
||||
num, ok = syscallNumExtra[name]
|
||||
return
|
||||
}
|
||||
48
container/seccomp/syscall_extra_linux_amd64.go
Normal file
48
container/seccomp/syscall_extra_linux_amd64.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package seccomp
|
||||
|
||||
/*
|
||||
#cgo linux pkg-config: --static libseccomp
|
||||
|
||||
#include <seccomp.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
var syscallNumExtra = map[string]int{
|
||||
"umount": SYS_UMOUNT,
|
||||
"subpage_prot": SYS_SUBPAGE_PROT,
|
||||
"switch_endian": SYS_SWITCH_ENDIAN,
|
||||
"vm86": SYS_VM86,
|
||||
"vm86old": SYS_VM86OLD,
|
||||
"clock_adjtime64": SYS_CLOCK_ADJTIME64,
|
||||
"clock_settime64": SYS_CLOCK_SETTIME64,
|
||||
"chown32": SYS_CHOWN32,
|
||||
"fchown32": SYS_FCHOWN32,
|
||||
"lchown32": SYS_LCHOWN32,
|
||||
"setgid32": SYS_SETGID32,
|
||||
"setgroups32": SYS_SETGROUPS32,
|
||||
"setregid32": SYS_SETREGID32,
|
||||
"setresgid32": SYS_SETRESGID32,
|
||||
"setresuid32": SYS_SETRESUID32,
|
||||
"setreuid32": SYS_SETREUID32,
|
||||
"setuid32": SYS_SETUID32,
|
||||
}
|
||||
|
||||
const (
|
||||
SYS_UMOUNT = C.__SNR_umount
|
||||
SYS_SUBPAGE_PROT = C.__SNR_subpage_prot
|
||||
SYS_SWITCH_ENDIAN = C.__SNR_switch_endian
|
||||
SYS_VM86 = C.__SNR_vm86
|
||||
SYS_VM86OLD = C.__SNR_vm86old
|
||||
SYS_CLOCK_ADJTIME64 = C.__SNR_clock_adjtime64
|
||||
SYS_CLOCK_SETTIME64 = C.__SNR_clock_settime64
|
||||
SYS_CHOWN32 = C.__SNR_chown32
|
||||
SYS_FCHOWN32 = C.__SNR_fchown32
|
||||
SYS_LCHOWN32 = C.__SNR_lchown32
|
||||
SYS_SETGID32 = C.__SNR_setgid32
|
||||
SYS_SETGROUPS32 = C.__SNR_setgroups32
|
||||
SYS_SETREGID32 = C.__SNR_setregid32
|
||||
SYS_SETRESGID32 = C.__SNR_setresgid32
|
||||
SYS_SETRESUID32 = C.__SNR_setresuid32
|
||||
SYS_SETREUID32 = C.__SNR_setreuid32
|
||||
SYS_SETUID32 = C.__SNR_setuid32
|
||||
)
|
||||
61
container/seccomp/syscall_extra_linux_arm64.go
Normal file
61
container/seccomp/syscall_extra_linux_arm64.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package seccomp
|
||||
|
||||
/*
|
||||
#cgo linux pkg-config: --static libseccomp
|
||||
|
||||
#include <seccomp.h>
|
||||
*/
|
||||
import "C"
|
||||
import "syscall"
|
||||
|
||||
const (
|
||||
SYS_NEWFSTATAT = syscall.SYS_FSTATAT
|
||||
)
|
||||
|
||||
var syscallNumExtra = map[string]int{
|
||||
"uselib": SYS_USELIB,
|
||||
"clock_adjtime64": SYS_CLOCK_ADJTIME64,
|
||||
"clock_settime64": SYS_CLOCK_SETTIME64,
|
||||
"umount": SYS_UMOUNT,
|
||||
"chown": SYS_CHOWN,
|
||||
"chown32": SYS_CHOWN32,
|
||||
"fchown32": SYS_FCHOWN32,
|
||||
"lchown": SYS_LCHOWN,
|
||||
"lchown32": SYS_LCHOWN32,
|
||||
"setgid32": SYS_SETGID32,
|
||||
"setgroups32": SYS_SETGROUPS32,
|
||||
"setregid32": SYS_SETREGID32,
|
||||
"setresgid32": SYS_SETRESGID32,
|
||||
"setresuid32": SYS_SETRESUID32,
|
||||
"setreuid32": SYS_SETREUID32,
|
||||
"setuid32": SYS_SETUID32,
|
||||
"modify_ldt": SYS_MODIFY_LDT,
|
||||
"subpage_prot": SYS_SUBPAGE_PROT,
|
||||
"switch_endian": SYS_SWITCH_ENDIAN,
|
||||
"vm86": SYS_VM86,
|
||||
"vm86old": SYS_VM86OLD,
|
||||
}
|
||||
|
||||
const (
|
||||
SYS_USELIB = C.__SNR_uselib
|
||||
SYS_CLOCK_ADJTIME64 = C.__SNR_clock_adjtime64
|
||||
SYS_CLOCK_SETTIME64 = C.__SNR_clock_settime64
|
||||
SYS_UMOUNT = C.__SNR_umount
|
||||
SYS_CHOWN = C.__SNR_chown
|
||||
SYS_CHOWN32 = C.__SNR_chown32
|
||||
SYS_FCHOWN32 = C.__SNR_fchown32
|
||||
SYS_LCHOWN = C.__SNR_lchown
|
||||
SYS_LCHOWN32 = C.__SNR_lchown32
|
||||
SYS_SETGID32 = C.__SNR_setgid32
|
||||
SYS_SETGROUPS32 = C.__SNR_setgroups32
|
||||
SYS_SETREGID32 = C.__SNR_setregid32
|
||||
SYS_SETRESGID32 = C.__SNR_setresgid32
|
||||
SYS_SETRESUID32 = C.__SNR_setresuid32
|
||||
SYS_SETREUID32 = C.__SNR_setreuid32
|
||||
SYS_SETUID32 = C.__SNR_setuid32
|
||||
SYS_MODIFY_LDT = C.__SNR_modify_ldt
|
||||
SYS_SUBPAGE_PROT = C.__SNR_subpage_prot
|
||||
SYS_SWITCH_ENDIAN = C.__SNR_switch_endian
|
||||
SYS_VM86 = C.__SNR_vm86
|
||||
SYS_VM86OLD = C.__SNR_vm86old
|
||||
)
|
||||
459
container/seccomp/syscall_linux_amd64.go
Normal file
459
container/seccomp/syscall_linux_amd64.go
Normal file
@@ -0,0 +1,459 @@
|
||||
// mksysnum_linux.pl /usr/include/asm/unistd_64.h
|
||||
// Code generated by the command above; DO NOT EDIT.
|
||||
|
||||
package seccomp
|
||||
|
||||
import . "syscall"
|
||||
|
||||
var syscallNum = map[string]int{
|
||||
"read": SYS_READ,
|
||||
"write": SYS_WRITE,
|
||||
"open": SYS_OPEN,
|
||||
"close": SYS_CLOSE,
|
||||
"stat": SYS_STAT,
|
||||
"fstat": SYS_FSTAT,
|
||||
"lstat": SYS_LSTAT,
|
||||
"poll": SYS_POLL,
|
||||
"lseek": SYS_LSEEK,
|
||||
"mmap": SYS_MMAP,
|
||||
"mprotect": SYS_MPROTECT,
|
||||
"munmap": SYS_MUNMAP,
|
||||
"brk": SYS_BRK,
|
||||
"rt_sigaction": SYS_RT_SIGACTION,
|
||||
"rt_sigprocmask": SYS_RT_SIGPROCMASK,
|
||||
"rt_sigreturn": SYS_RT_SIGRETURN,
|
||||
"ioctl": SYS_IOCTL,
|
||||
"pread64": SYS_PREAD64,
|
||||
"pwrite64": SYS_PWRITE64,
|
||||
"readv": SYS_READV,
|
||||
"writev": SYS_WRITEV,
|
||||
"access": SYS_ACCESS,
|
||||
"pipe": SYS_PIPE,
|
||||
"select": SYS_SELECT,
|
||||
"sched_yield": SYS_SCHED_YIELD,
|
||||
"mremap": SYS_MREMAP,
|
||||
"msync": SYS_MSYNC,
|
||||
"mincore": SYS_MINCORE,
|
||||
"madvise": SYS_MADVISE,
|
||||
"shmget": SYS_SHMGET,
|
||||
"shmat": SYS_SHMAT,
|
||||
"shmctl": SYS_SHMCTL,
|
||||
"dup": SYS_DUP,
|
||||
"dup2": SYS_DUP2,
|
||||
"pause": SYS_PAUSE,
|
||||
"nanosleep": SYS_NANOSLEEP,
|
||||
"getitimer": SYS_GETITIMER,
|
||||
"alarm": SYS_ALARM,
|
||||
"setitimer": SYS_SETITIMER,
|
||||
"getpid": SYS_GETPID,
|
||||
"sendfile": SYS_SENDFILE,
|
||||
"socket": SYS_SOCKET,
|
||||
"connect": SYS_CONNECT,
|
||||
"accept": SYS_ACCEPT,
|
||||
"sendto": SYS_SENDTO,
|
||||
"recvfrom": SYS_RECVFROM,
|
||||
"sendmsg": SYS_SENDMSG,
|
||||
"recvmsg": SYS_RECVMSG,
|
||||
"shutdown": SYS_SHUTDOWN,
|
||||
"bind": SYS_BIND,
|
||||
"listen": SYS_LISTEN,
|
||||
"getsockname": SYS_GETSOCKNAME,
|
||||
"getpeername": SYS_GETPEERNAME,
|
||||
"socketpair": SYS_SOCKETPAIR,
|
||||
"setsockopt": SYS_SETSOCKOPT,
|
||||
"getsockopt": SYS_GETSOCKOPT,
|
||||
"clone": SYS_CLONE,
|
||||
"fork": SYS_FORK,
|
||||
"vfork": SYS_VFORK,
|
||||
"execve": SYS_EXECVE,
|
||||
"exit": SYS_EXIT,
|
||||
"wait4": SYS_WAIT4,
|
||||
"kill": SYS_KILL,
|
||||
"uname": SYS_UNAME,
|
||||
"semget": SYS_SEMGET,
|
||||
"semop": SYS_SEMOP,
|
||||
"semctl": SYS_SEMCTL,
|
||||
"shmdt": SYS_SHMDT,
|
||||
"msgget": SYS_MSGGET,
|
||||
"msgsnd": SYS_MSGSND,
|
||||
"msgrcv": SYS_MSGRCV,
|
||||
"msgctl": SYS_MSGCTL,
|
||||
"fcntl": SYS_FCNTL,
|
||||
"flock": SYS_FLOCK,
|
||||
"fsync": SYS_FSYNC,
|
||||
"fdatasync": SYS_FDATASYNC,
|
||||
"truncate": SYS_TRUNCATE,
|
||||
"ftruncate": SYS_FTRUNCATE,
|
||||
"getdents": SYS_GETDENTS,
|
||||
"getcwd": SYS_GETCWD,
|
||||
"chdir": SYS_CHDIR,
|
||||
"fchdir": SYS_FCHDIR,
|
||||
"rename": SYS_RENAME,
|
||||
"mkdir": SYS_MKDIR,
|
||||
"rmdir": SYS_RMDIR,
|
||||
"creat": SYS_CREAT,
|
||||
"link": SYS_LINK,
|
||||
"unlink": SYS_UNLINK,
|
||||
"symlink": SYS_SYMLINK,
|
||||
"readlink": SYS_READLINK,
|
||||
"chmod": SYS_CHMOD,
|
||||
"fchmod": SYS_FCHMOD,
|
||||
"chown": SYS_CHOWN,
|
||||
"fchown": SYS_FCHOWN,
|
||||
"lchown": SYS_LCHOWN,
|
||||
"umask": SYS_UMASK,
|
||||
"gettimeofday": SYS_GETTIMEOFDAY,
|
||||
"getrlimit": SYS_GETRLIMIT,
|
||||
"getrusage": SYS_GETRUSAGE,
|
||||
"sysinfo": SYS_SYSINFO,
|
||||
"times": SYS_TIMES,
|
||||
"ptrace": SYS_PTRACE,
|
||||
"getuid": SYS_GETUID,
|
||||
"syslog": SYS_SYSLOG,
|
||||
"getgid": SYS_GETGID,
|
||||
"setuid": SYS_SETUID,
|
||||
"setgid": SYS_SETGID,
|
||||
"geteuid": SYS_GETEUID,
|
||||
"getegid": SYS_GETEGID,
|
||||
"setpgid": SYS_SETPGID,
|
||||
"getppid": SYS_GETPPID,
|
||||
"getpgrp": SYS_GETPGRP,
|
||||
"setsid": SYS_SETSID,
|
||||
"setreuid": SYS_SETREUID,
|
||||
"setregid": SYS_SETREGID,
|
||||
"getgroups": SYS_GETGROUPS,
|
||||
"setgroups": SYS_SETGROUPS,
|
||||
"setresuid": SYS_SETRESUID,
|
||||
"getresuid": SYS_GETRESUID,
|
||||
"setresgid": SYS_SETRESGID,
|
||||
"getresgid": SYS_GETRESGID,
|
||||
"getpgid": SYS_GETPGID,
|
||||
"setfsuid": SYS_SETFSUID,
|
||||
"setfsgid": SYS_SETFSGID,
|
||||
"getsid": SYS_GETSID,
|
||||
"capget": SYS_CAPGET,
|
||||
"capset": SYS_CAPSET,
|
||||
"rt_sigpending": SYS_RT_SIGPENDING,
|
||||
"rt_sigtimedwait": SYS_RT_SIGTIMEDWAIT,
|
||||
"rt_sigqueueinfo": SYS_RT_SIGQUEUEINFO,
|
||||
"rt_sigsuspend": SYS_RT_SIGSUSPEND,
|
||||
"sigaltstack": SYS_SIGALTSTACK,
|
||||
"utime": SYS_UTIME,
|
||||
"mknod": SYS_MKNOD,
|
||||
"uselib": SYS_USELIB,
|
||||
"personality": SYS_PERSONALITY,
|
||||
"ustat": SYS_USTAT,
|
||||
"statfs": SYS_STATFS,
|
||||
"fstatfs": SYS_FSTATFS,
|
||||
"sysfs": SYS_SYSFS,
|
||||
"getpriority": SYS_GETPRIORITY,
|
||||
"setpriority": SYS_SETPRIORITY,
|
||||
"sched_setparam": SYS_SCHED_SETPARAM,
|
||||
"sched_getparam": SYS_SCHED_GETPARAM,
|
||||
"sched_setscheduler": SYS_SCHED_SETSCHEDULER,
|
||||
"sched_getscheduler": SYS_SCHED_GETSCHEDULER,
|
||||
"sched_get_priority_max": SYS_SCHED_GET_PRIORITY_MAX,
|
||||
"sched_get_priority_min": SYS_SCHED_GET_PRIORITY_MIN,
|
||||
"sched_rr_get_interval": SYS_SCHED_RR_GET_INTERVAL,
|
||||
"mlock": SYS_MLOCK,
|
||||
"munlock": SYS_MUNLOCK,
|
||||
"mlockall": SYS_MLOCKALL,
|
||||
"munlockall": SYS_MUNLOCKALL,
|
||||
"vhangup": SYS_VHANGUP,
|
||||
"modify_ldt": SYS_MODIFY_LDT,
|
||||
"pivot_root": SYS_PIVOT_ROOT,
|
||||
"_sysctl": SYS__SYSCTL,
|
||||
"prctl": SYS_PRCTL,
|
||||
"arch_prctl": SYS_ARCH_PRCTL,
|
||||
"adjtimex": SYS_ADJTIMEX,
|
||||
"setrlimit": SYS_SETRLIMIT,
|
||||
"chroot": SYS_CHROOT,
|
||||
"sync": SYS_SYNC,
|
||||
"acct": SYS_ACCT,
|
||||
"settimeofday": SYS_SETTIMEOFDAY,
|
||||
"mount": SYS_MOUNT,
|
||||
"umount2": SYS_UMOUNT2,
|
||||
"swapon": SYS_SWAPON,
|
||||
"swapoff": SYS_SWAPOFF,
|
||||
"reboot": SYS_REBOOT,
|
||||
"sethostname": SYS_SETHOSTNAME,
|
||||
"setdomainname": SYS_SETDOMAINNAME,
|
||||
"iopl": SYS_IOPL,
|
||||
"ioperm": SYS_IOPERM,
|
||||
"create_module": SYS_CREATE_MODULE,
|
||||
"init_module": SYS_INIT_MODULE,
|
||||
"delete_module": SYS_DELETE_MODULE,
|
||||
"get_kernel_syms": SYS_GET_KERNEL_SYMS,
|
||||
"query_module": SYS_QUERY_MODULE,
|
||||
"quotactl": SYS_QUOTACTL,
|
||||
"nfsservctl": SYS_NFSSERVCTL,
|
||||
"getpmsg": SYS_GETPMSG,
|
||||
"putpmsg": SYS_PUTPMSG,
|
||||
"afs_syscall": SYS_AFS_SYSCALL,
|
||||
"tuxcall": SYS_TUXCALL,
|
||||
"security": SYS_SECURITY,
|
||||
"gettid": SYS_GETTID,
|
||||
"readahead": SYS_READAHEAD,
|
||||
"setxattr": SYS_SETXATTR,
|
||||
"lsetxattr": SYS_LSETXATTR,
|
||||
"fsetxattr": SYS_FSETXATTR,
|
||||
"getxattr": SYS_GETXATTR,
|
||||
"lgetxattr": SYS_LGETXATTR,
|
||||
"fgetxattr": SYS_FGETXATTR,
|
||||
"listxattr": SYS_LISTXATTR,
|
||||
"llistxattr": SYS_LLISTXATTR,
|
||||
"flistxattr": SYS_FLISTXATTR,
|
||||
"removexattr": SYS_REMOVEXATTR,
|
||||
"lremovexattr": SYS_LREMOVEXATTR,
|
||||
"fremovexattr": SYS_FREMOVEXATTR,
|
||||
"tkill": SYS_TKILL,
|
||||
"time": SYS_TIME,
|
||||
"futex": SYS_FUTEX,
|
||||
"sched_setaffinity": SYS_SCHED_SETAFFINITY,
|
||||
"sched_getaffinity": SYS_SCHED_GETAFFINITY,
|
||||
"set_thread_area": SYS_SET_THREAD_AREA,
|
||||
"io_setup": SYS_IO_SETUP,
|
||||
"io_destroy": SYS_IO_DESTROY,
|
||||
"io_getevents": SYS_IO_GETEVENTS,
|
||||
"io_submit": SYS_IO_SUBMIT,
|
||||
"io_cancel": SYS_IO_CANCEL,
|
||||
"get_thread_area": SYS_GET_THREAD_AREA,
|
||||
"lookup_dcookie": SYS_LOOKUP_DCOOKIE,
|
||||
"epoll_create": SYS_EPOLL_CREATE,
|
||||
"epoll_ctl_old": SYS_EPOLL_CTL_OLD,
|
||||
"epoll_wait_old": SYS_EPOLL_WAIT_OLD,
|
||||
"remap_file_pages": SYS_REMAP_FILE_PAGES,
|
||||
"getdents64": SYS_GETDENTS64,
|
||||
"set_tid_address": SYS_SET_TID_ADDRESS,
|
||||
"restart_syscall": SYS_RESTART_SYSCALL,
|
||||
"semtimedop": SYS_SEMTIMEDOP,
|
||||
"fadvise64": SYS_FADVISE64,
|
||||
"timer_create": SYS_TIMER_CREATE,
|
||||
"timer_settime": SYS_TIMER_SETTIME,
|
||||
"timer_gettime": SYS_TIMER_GETTIME,
|
||||
"timer_getoverrun": SYS_TIMER_GETOVERRUN,
|
||||
"timer_delete": SYS_TIMER_DELETE,
|
||||
"clock_settime": SYS_CLOCK_SETTIME,
|
||||
"clock_gettime": SYS_CLOCK_GETTIME,
|
||||
"clock_getres": SYS_CLOCK_GETRES,
|
||||
"clock_nanosleep": SYS_CLOCK_NANOSLEEP,
|
||||
"exit_group": SYS_EXIT_GROUP,
|
||||
"epoll_wait": SYS_EPOLL_WAIT,
|
||||
"epoll_ctl": SYS_EPOLL_CTL,
|
||||
"tgkill": SYS_TGKILL,
|
||||
"utimes": SYS_UTIMES,
|
||||
"vserver": SYS_VSERVER,
|
||||
"mbind": SYS_MBIND,
|
||||
"set_mempolicy": SYS_SET_MEMPOLICY,
|
||||
"get_mempolicy": SYS_GET_MEMPOLICY,
|
||||
"mq_open": SYS_MQ_OPEN,
|
||||
"mq_unlink": SYS_MQ_UNLINK,
|
||||
"mq_timedsend": SYS_MQ_TIMEDSEND,
|
||||
"mq_timedreceive": SYS_MQ_TIMEDRECEIVE,
|
||||
"mq_notify": SYS_MQ_NOTIFY,
|
||||
"mq_getsetattr": SYS_MQ_GETSETATTR,
|
||||
"kexec_load": SYS_KEXEC_LOAD,
|
||||
"waitid": SYS_WAITID,
|
||||
"add_key": SYS_ADD_KEY,
|
||||
"request_key": SYS_REQUEST_KEY,
|
||||
"keyctl": SYS_KEYCTL,
|
||||
"ioprio_set": SYS_IOPRIO_SET,
|
||||
"ioprio_get": SYS_IOPRIO_GET,
|
||||
"inotify_init": SYS_INOTIFY_INIT,
|
||||
"inotify_add_watch": SYS_INOTIFY_ADD_WATCH,
|
||||
"inotify_rm_watch": SYS_INOTIFY_RM_WATCH,
|
||||
"migrate_pages": SYS_MIGRATE_PAGES,
|
||||
"openat": SYS_OPENAT,
|
||||
"mkdirat": SYS_MKDIRAT,
|
||||
"mknodat": SYS_MKNODAT,
|
||||
"fchownat": SYS_FCHOWNAT,
|
||||
"futimesat": SYS_FUTIMESAT,
|
||||
"newfstatat": SYS_NEWFSTATAT,
|
||||
"unlinkat": SYS_UNLINKAT,
|
||||
"renameat": SYS_RENAMEAT,
|
||||
"linkat": SYS_LINKAT,
|
||||
"symlinkat": SYS_SYMLINKAT,
|
||||
"readlinkat": SYS_READLINKAT,
|
||||
"fchmodat": SYS_FCHMODAT,
|
||||
"faccessat": SYS_FACCESSAT,
|
||||
"pselect6": SYS_PSELECT6,
|
||||
"ppoll": SYS_PPOLL,
|
||||
"unshare": SYS_UNSHARE,
|
||||
"set_robust_list": SYS_SET_ROBUST_LIST,
|
||||
"get_robust_list": SYS_GET_ROBUST_LIST,
|
||||
"splice": SYS_SPLICE,
|
||||
"tee": SYS_TEE,
|
||||
"sync_file_range": SYS_SYNC_FILE_RANGE,
|
||||
"vmsplice": SYS_VMSPLICE,
|
||||
"move_pages": SYS_MOVE_PAGES,
|
||||
"utimensat": SYS_UTIMENSAT,
|
||||
"epoll_pwait": SYS_EPOLL_PWAIT,
|
||||
"signalfd": SYS_SIGNALFD,
|
||||
"timerfd_create": SYS_TIMERFD_CREATE,
|
||||
"eventfd": SYS_EVENTFD,
|
||||
"fallocate": SYS_FALLOCATE,
|
||||
"timerfd_settime": SYS_TIMERFD_SETTIME,
|
||||
"timerfd_gettime": SYS_TIMERFD_GETTIME,
|
||||
"accept4": SYS_ACCEPT4,
|
||||
"signalfd4": SYS_SIGNALFD4,
|
||||
"eventfd2": SYS_EVENTFD2,
|
||||
"epoll_create1": SYS_EPOLL_CREATE1,
|
||||
"dup3": SYS_DUP3,
|
||||
"pipe2": SYS_PIPE2,
|
||||
"inotify_init1": SYS_INOTIFY_INIT1,
|
||||
"preadv": SYS_PREADV,
|
||||
"pwritev": SYS_PWRITEV,
|
||||
"rt_tgsigqueueinfo": SYS_RT_TGSIGQUEUEINFO,
|
||||
"perf_event_open": SYS_PERF_EVENT_OPEN,
|
||||
"recvmmsg": SYS_RECVMMSG,
|
||||
"fanotify_init": SYS_FANOTIFY_INIT,
|
||||
"fanotify_mark": SYS_FANOTIFY_MARK,
|
||||
"prlimit64": SYS_PRLIMIT64,
|
||||
"name_to_handle_at": SYS_NAME_TO_HANDLE_AT,
|
||||
"open_by_handle_at": SYS_OPEN_BY_HANDLE_AT,
|
||||
"clock_adjtime": SYS_CLOCK_ADJTIME,
|
||||
"syncfs": SYS_SYNCFS,
|
||||
"sendmmsg": SYS_SENDMMSG,
|
||||
"setns": SYS_SETNS,
|
||||
"getcpu": SYS_GETCPU,
|
||||
"process_vm_readv": SYS_PROCESS_VM_READV,
|
||||
"process_vm_writev": SYS_PROCESS_VM_WRITEV,
|
||||
"kcmp": SYS_KCMP,
|
||||
"finit_module": SYS_FINIT_MODULE,
|
||||
"sched_setattr": SYS_SCHED_SETATTR,
|
||||
"sched_getattr": SYS_SCHED_GETATTR,
|
||||
"renameat2": SYS_RENAMEAT2,
|
||||
"seccomp": SYS_SECCOMP,
|
||||
"getrandom": SYS_GETRANDOM,
|
||||
"memfd_create": SYS_MEMFD_CREATE,
|
||||
"kexec_file_load": SYS_KEXEC_FILE_LOAD,
|
||||
"bpf": SYS_BPF,
|
||||
"execveat": SYS_EXECVEAT,
|
||||
"userfaultfd": SYS_USERFAULTFD,
|
||||
"membarrier": SYS_MEMBARRIER,
|
||||
"mlock2": SYS_MLOCK2,
|
||||
"copy_file_range": SYS_COPY_FILE_RANGE,
|
||||
"preadv2": SYS_PREADV2,
|
||||
"pwritev2": SYS_PWRITEV2,
|
||||
"pkey_mprotect": SYS_PKEY_MPROTECT,
|
||||
"pkey_alloc": SYS_PKEY_ALLOC,
|
||||
"pkey_free": SYS_PKEY_FREE,
|
||||
"statx": SYS_STATX,
|
||||
"io_pgetevents": SYS_IO_PGETEVENTS,
|
||||
"rseq": SYS_RSEQ,
|
||||
"uretprobe": SYS_URETPROBE,
|
||||
"pidfd_send_signal": SYS_PIDFD_SEND_SIGNAL,
|
||||
"io_uring_setup": SYS_IO_URING_SETUP,
|
||||
"io_uring_enter": SYS_IO_URING_ENTER,
|
||||
"io_uring_register": SYS_IO_URING_REGISTER,
|
||||
"open_tree": SYS_OPEN_TREE,
|
||||
"move_mount": SYS_MOVE_MOUNT,
|
||||
"fsopen": SYS_FSOPEN,
|
||||
"fsconfig": SYS_FSCONFIG,
|
||||
"fsmount": SYS_FSMOUNT,
|
||||
"fspick": SYS_FSPICK,
|
||||
"pidfd_open": SYS_PIDFD_OPEN,
|
||||
"clone3": SYS_CLONE3,
|
||||
"close_range": SYS_CLOSE_RANGE,
|
||||
"openat2": SYS_OPENAT2,
|
||||
"pidfd_getfd": SYS_PIDFD_GETFD,
|
||||
"faccessat2": SYS_FACCESSAT2,
|
||||
"process_madvise": SYS_PROCESS_MADVISE,
|
||||
"epoll_pwait2": SYS_EPOLL_PWAIT2,
|
||||
"mount_setattr": SYS_MOUNT_SETATTR,
|
||||
"quotactl_fd": SYS_QUOTACTL_FD,
|
||||
"landlock_create_ruleset": SYS_LANDLOCK_CREATE_RULESET,
|
||||
"landlock_add_rule": SYS_LANDLOCK_ADD_RULE,
|
||||
"landlock_restrict_self": SYS_LANDLOCK_RESTRICT_SELF,
|
||||
"memfd_secret": SYS_MEMFD_SECRET,
|
||||
"process_mrelease": SYS_PROCESS_MRELEASE,
|
||||
"futex_waitv": SYS_FUTEX_WAITV,
|
||||
"set_mempolicy_home_node": SYS_SET_MEMPOLICY_HOME_NODE,
|
||||
"cachestat": SYS_CACHESTAT,
|
||||
"fchmodat2": SYS_FCHMODAT2,
|
||||
"map_shadow_stack": SYS_MAP_SHADOW_STACK,
|
||||
"futex_wake": SYS_FUTEX_WAKE,
|
||||
"futex_wait": SYS_FUTEX_WAIT,
|
||||
"futex_requeue": SYS_FUTEX_REQUEUE,
|
||||
"statmount": SYS_STATMOUNT,
|
||||
"listmount": SYS_LISTMOUNT,
|
||||
"lsm_get_self_attr": SYS_LSM_GET_SELF_ATTR,
|
||||
"lsm_set_self_attr": SYS_LSM_SET_SELF_ATTR,
|
||||
"lsm_list_modules": SYS_LSM_LIST_MODULES,
|
||||
"mseal": SYS_MSEAL,
|
||||
}
|
||||
|
||||
const (
|
||||
SYS_NAME_TO_HANDLE_AT = 303
|
||||
SYS_OPEN_BY_HANDLE_AT = 304
|
||||
SYS_CLOCK_ADJTIME = 305
|
||||
SYS_SYNCFS = 306
|
||||
SYS_SENDMMSG = 307
|
||||
SYS_SETNS = 308
|
||||
SYS_GETCPU = 309
|
||||
SYS_PROCESS_VM_READV = 310
|
||||
SYS_PROCESS_VM_WRITEV = 311
|
||||
SYS_KCMP = 312
|
||||
SYS_FINIT_MODULE = 313
|
||||
SYS_SCHED_SETATTR = 314
|
||||
SYS_SCHED_GETATTR = 315
|
||||
SYS_RENAMEAT2 = 316
|
||||
SYS_SECCOMP = 317
|
||||
SYS_GETRANDOM = 318
|
||||
SYS_MEMFD_CREATE = 319
|
||||
SYS_KEXEC_FILE_LOAD = 320
|
||||
SYS_BPF = 321
|
||||
SYS_EXECVEAT = 322
|
||||
SYS_USERFAULTFD = 323
|
||||
SYS_MEMBARRIER = 324
|
||||
SYS_MLOCK2 = 325
|
||||
SYS_COPY_FILE_RANGE = 326
|
||||
SYS_PREADV2 = 327
|
||||
SYS_PWRITEV2 = 328
|
||||
SYS_PKEY_MPROTECT = 329
|
||||
SYS_PKEY_ALLOC = 330
|
||||
SYS_PKEY_FREE = 331
|
||||
SYS_STATX = 332
|
||||
SYS_IO_PGETEVENTS = 333
|
||||
SYS_RSEQ = 334
|
||||
SYS_URETPROBE = 335
|
||||
SYS_PIDFD_SEND_SIGNAL = 424
|
||||
SYS_IO_URING_SETUP = 425
|
||||
SYS_IO_URING_ENTER = 426
|
||||
SYS_IO_URING_REGISTER = 427
|
||||
SYS_OPEN_TREE = 428
|
||||
SYS_MOVE_MOUNT = 429
|
||||
SYS_FSOPEN = 430
|
||||
SYS_FSCONFIG = 431
|
||||
SYS_FSMOUNT = 432
|
||||
SYS_FSPICK = 433
|
||||
SYS_PIDFD_OPEN = 434
|
||||
SYS_CLONE3 = 435
|
||||
SYS_CLOSE_RANGE = 436
|
||||
SYS_OPENAT2 = 437
|
||||
SYS_PIDFD_GETFD = 438
|
||||
SYS_FACCESSAT2 = 439
|
||||
SYS_PROCESS_MADVISE = 440
|
||||
SYS_EPOLL_PWAIT2 = 441
|
||||
SYS_MOUNT_SETATTR = 442
|
||||
SYS_QUOTACTL_FD = 443
|
||||
SYS_LANDLOCK_CREATE_RULESET = 444
|
||||
SYS_LANDLOCK_ADD_RULE = 445
|
||||
SYS_LANDLOCK_RESTRICT_SELF = 446
|
||||
SYS_MEMFD_SECRET = 447
|
||||
SYS_PROCESS_MRELEASE = 448
|
||||
SYS_FUTEX_WAITV = 449
|
||||
SYS_SET_MEMPOLICY_HOME_NODE = 450
|
||||
SYS_CACHESTAT = 451
|
||||
SYS_FCHMODAT2 = 452
|
||||
SYS_MAP_SHADOW_STACK = 453
|
||||
SYS_FUTEX_WAKE = 454
|
||||
SYS_FUTEX_WAIT = 455
|
||||
SYS_FUTEX_REQUEUE = 456
|
||||
SYS_STATMOUNT = 457
|
||||
SYS_LISTMOUNT = 458
|
||||
SYS_LSM_GET_SELF_ATTR = 459
|
||||
SYS_LSM_SET_SELF_ATTR = 460
|
||||
SYS_LSM_LIST_MODULES = 461
|
||||
SYS_MSEAL = 462
|
||||
)
|
||||
382
container/seccomp/syscall_linux_arm64.go
Normal file
382
container/seccomp/syscall_linux_arm64.go
Normal file
@@ -0,0 +1,382 @@
|
||||
// mksysnum_linux.pl /usr/include/asm/unistd_64.h
|
||||
// Code generated by the command above; DO NOT EDIT.
|
||||
|
||||
package seccomp
|
||||
|
||||
import . "syscall"
|
||||
|
||||
var syscallNum = map[string]int{
|
||||
"io_setup": SYS_IO_SETUP,
|
||||
"io_destroy": SYS_IO_DESTROY,
|
||||
"io_submit": SYS_IO_SUBMIT,
|
||||
"io_cancel": SYS_IO_CANCEL,
|
||||
"io_getevents": SYS_IO_GETEVENTS,
|
||||
"setxattr": SYS_SETXATTR,
|
||||
"lsetxattr": SYS_LSETXATTR,
|
||||
"fsetxattr": SYS_FSETXATTR,
|
||||
"getxattr": SYS_GETXATTR,
|
||||
"lgetxattr": SYS_LGETXATTR,
|
||||
"fgetxattr": SYS_FGETXATTR,
|
||||
"listxattr": SYS_LISTXATTR,
|
||||
"llistxattr": SYS_LLISTXATTR,
|
||||
"flistxattr": SYS_FLISTXATTR,
|
||||
"removexattr": SYS_REMOVEXATTR,
|
||||
"lremovexattr": SYS_LREMOVEXATTR,
|
||||
"fremovexattr": SYS_FREMOVEXATTR,
|
||||
"getcwd": SYS_GETCWD,
|
||||
"lookup_dcookie": SYS_LOOKUP_DCOOKIE,
|
||||
"eventfd2": SYS_EVENTFD2,
|
||||
"epoll_create1": SYS_EPOLL_CREATE1,
|
||||
"epoll_ctl": SYS_EPOLL_CTL,
|
||||
"epoll_pwait": SYS_EPOLL_PWAIT,
|
||||
"dup": SYS_DUP,
|
||||
"dup3": SYS_DUP3,
|
||||
"fcntl": SYS_FCNTL,
|
||||
"inotify_init1": SYS_INOTIFY_INIT1,
|
||||
"inotify_add_watch": SYS_INOTIFY_ADD_WATCH,
|
||||
"inotify_rm_watch": SYS_INOTIFY_RM_WATCH,
|
||||
"ioctl": SYS_IOCTL,
|
||||
"ioprio_set": SYS_IOPRIO_SET,
|
||||
"ioprio_get": SYS_IOPRIO_GET,
|
||||
"flock": SYS_FLOCK,
|
||||
"mknodat": SYS_MKNODAT,
|
||||
"mkdirat": SYS_MKDIRAT,
|
||||
"unlinkat": SYS_UNLINKAT,
|
||||
"symlinkat": SYS_SYMLINKAT,
|
||||
"linkat": SYS_LINKAT,
|
||||
"renameat": SYS_RENAMEAT,
|
||||
"umount2": SYS_UMOUNT2,
|
||||
"mount": SYS_MOUNT,
|
||||
"pivot_root": SYS_PIVOT_ROOT,
|
||||
"nfsservctl": SYS_NFSSERVCTL,
|
||||
"statfs": SYS_STATFS,
|
||||
"fstatfs": SYS_FSTATFS,
|
||||
"truncate": SYS_TRUNCATE,
|
||||
"ftruncate": SYS_FTRUNCATE,
|
||||
"fallocate": SYS_FALLOCATE,
|
||||
"faccessat": SYS_FACCESSAT,
|
||||
"chdir": SYS_CHDIR,
|
||||
"fchdir": SYS_FCHDIR,
|
||||
"chroot": SYS_CHROOT,
|
||||
"fchmod": SYS_FCHMOD,
|
||||
"fchmodat": SYS_FCHMODAT,
|
||||
"fchownat": SYS_FCHOWNAT,
|
||||
"fchown": SYS_FCHOWN,
|
||||
"openat": SYS_OPENAT,
|
||||
"close": SYS_CLOSE,
|
||||
"vhangup": SYS_VHANGUP,
|
||||
"pipe2": SYS_PIPE2,
|
||||
"quotactl": SYS_QUOTACTL,
|
||||
"getdents64": SYS_GETDENTS64,
|
||||
"lseek": SYS_LSEEK,
|
||||
"read": SYS_READ,
|
||||
"write": SYS_WRITE,
|
||||
"readv": SYS_READV,
|
||||
"writev": SYS_WRITEV,
|
||||
"pread64": SYS_PREAD64,
|
||||
"pwrite64": SYS_PWRITE64,
|
||||
"preadv": SYS_PREADV,
|
||||
"pwritev": SYS_PWRITEV,
|
||||
"sendfile": SYS_SENDFILE,
|
||||
"pselect6": SYS_PSELECT6,
|
||||
"ppoll": SYS_PPOLL,
|
||||
"signalfd4": SYS_SIGNALFD4,
|
||||
"vmsplice": SYS_VMSPLICE,
|
||||
"splice": SYS_SPLICE,
|
||||
"tee": SYS_TEE,
|
||||
"readlinkat": SYS_READLINKAT,
|
||||
"newfstatat": SYS_NEWFSTATAT,
|
||||
"fstat": SYS_FSTAT,
|
||||
"sync": SYS_SYNC,
|
||||
"fsync": SYS_FSYNC,
|
||||
"fdatasync": SYS_FDATASYNC,
|
||||
"sync_file_range": SYS_SYNC_FILE_RANGE,
|
||||
"timerfd_create": SYS_TIMERFD_CREATE,
|
||||
"timerfd_settime": SYS_TIMERFD_SETTIME,
|
||||
"timerfd_gettime": SYS_TIMERFD_GETTIME,
|
||||
"utimensat": SYS_UTIMENSAT,
|
||||
"acct": SYS_ACCT,
|
||||
"capget": SYS_CAPGET,
|
||||
"capset": SYS_CAPSET,
|
||||
"personality": SYS_PERSONALITY,
|
||||
"exit": SYS_EXIT,
|
||||
"exit_group": SYS_EXIT_GROUP,
|
||||
"waitid": SYS_WAITID,
|
||||
"set_tid_address": SYS_SET_TID_ADDRESS,
|
||||
"unshare": SYS_UNSHARE,
|
||||
"futex": SYS_FUTEX,
|
||||
"set_robust_list": SYS_SET_ROBUST_LIST,
|
||||
"get_robust_list": SYS_GET_ROBUST_LIST,
|
||||
"nanosleep": SYS_NANOSLEEP,
|
||||
"getitimer": SYS_GETITIMER,
|
||||
"setitimer": SYS_SETITIMER,
|
||||
"kexec_load": SYS_KEXEC_LOAD,
|
||||
"init_module": SYS_INIT_MODULE,
|
||||
"delete_module": SYS_DELETE_MODULE,
|
||||
"timer_create": SYS_TIMER_CREATE,
|
||||
"timer_gettime": SYS_TIMER_GETTIME,
|
||||
"timer_getoverrun": SYS_TIMER_GETOVERRUN,
|
||||
"timer_settime": SYS_TIMER_SETTIME,
|
||||
"timer_delete": SYS_TIMER_DELETE,
|
||||
"clock_settime": SYS_CLOCK_SETTIME,
|
||||
"clock_gettime": SYS_CLOCK_GETTIME,
|
||||
"clock_getres": SYS_CLOCK_GETRES,
|
||||
"clock_nanosleep": SYS_CLOCK_NANOSLEEP,
|
||||
"syslog": SYS_SYSLOG,
|
||||
"ptrace": SYS_PTRACE,
|
||||
"sched_setparam": SYS_SCHED_SETPARAM,
|
||||
"sched_setscheduler": SYS_SCHED_SETSCHEDULER,
|
||||
"sched_getscheduler": SYS_SCHED_GETSCHEDULER,
|
||||
"sched_getparam": SYS_SCHED_GETPARAM,
|
||||
"sched_setaffinity": SYS_SCHED_SETAFFINITY,
|
||||
"sched_getaffinity": SYS_SCHED_GETAFFINITY,
|
||||
"sched_yield": SYS_SCHED_YIELD,
|
||||
"sched_get_priority_max": SYS_SCHED_GET_PRIORITY_MAX,
|
||||
"sched_get_priority_min": SYS_SCHED_GET_PRIORITY_MIN,
|
||||
"sched_rr_get_interval": SYS_SCHED_RR_GET_INTERVAL,
|
||||
"restart_syscall": SYS_RESTART_SYSCALL,
|
||||
"kill": SYS_KILL,
|
||||
"tkill": SYS_TKILL,
|
||||
"tgkill": SYS_TGKILL,
|
||||
"sigaltstack": SYS_SIGALTSTACK,
|
||||
"rt_sigsuspend": SYS_RT_SIGSUSPEND,
|
||||
"rt_sigaction": SYS_RT_SIGACTION,
|
||||
"rt_sigprocmask": SYS_RT_SIGPROCMASK,
|
||||
"rt_sigpending": SYS_RT_SIGPENDING,
|
||||
"rt_sigtimedwait": SYS_RT_SIGTIMEDWAIT,
|
||||
"rt_sigqueueinfo": SYS_RT_SIGQUEUEINFO,
|
||||
"rt_sigreturn": SYS_RT_SIGRETURN,
|
||||
"setpriority": SYS_SETPRIORITY,
|
||||
"getpriority": SYS_GETPRIORITY,
|
||||
"reboot": SYS_REBOOT,
|
||||
"setregid": SYS_SETREGID,
|
||||
"setgid": SYS_SETGID,
|
||||
"setreuid": SYS_SETREUID,
|
||||
"setuid": SYS_SETUID,
|
||||
"setresuid": SYS_SETRESUID,
|
||||
"getresuid": SYS_GETRESUID,
|
||||
"setresgid": SYS_SETRESGID,
|
||||
"getresgid": SYS_GETRESGID,
|
||||
"setfsuid": SYS_SETFSUID,
|
||||
"setfsgid": SYS_SETFSGID,
|
||||
"times": SYS_TIMES,
|
||||
"setpgid": SYS_SETPGID,
|
||||
"getpgid": SYS_GETPGID,
|
||||
"getsid": SYS_GETSID,
|
||||
"setsid": SYS_SETSID,
|
||||
"getgroups": SYS_GETGROUPS,
|
||||
"setgroups": SYS_SETGROUPS,
|
||||
"uname": SYS_UNAME,
|
||||
"sethostname": SYS_SETHOSTNAME,
|
||||
"setdomainname": SYS_SETDOMAINNAME,
|
||||
"getrlimit": SYS_GETRLIMIT,
|
||||
"setrlimit": SYS_SETRLIMIT,
|
||||
"getrusage": SYS_GETRUSAGE,
|
||||
"umask": SYS_UMASK,
|
||||
"prctl": SYS_PRCTL,
|
||||
"getcpu": SYS_GETCPU,
|
||||
"gettimeofday": SYS_GETTIMEOFDAY,
|
||||
"settimeofday": SYS_SETTIMEOFDAY,
|
||||
"adjtimex": SYS_ADJTIMEX,
|
||||
"getpid": SYS_GETPID,
|
||||
"getppid": SYS_GETPPID,
|
||||
"getuid": SYS_GETUID,
|
||||
"geteuid": SYS_GETEUID,
|
||||
"getgid": SYS_GETGID,
|
||||
"getegid": SYS_GETEGID,
|
||||
"gettid": SYS_GETTID,
|
||||
"sysinfo": SYS_SYSINFO,
|
||||
"mq_open": SYS_MQ_OPEN,
|
||||
"mq_unlink": SYS_MQ_UNLINK,
|
||||
"mq_timedsend": SYS_MQ_TIMEDSEND,
|
||||
"mq_timedreceive": SYS_MQ_TIMEDRECEIVE,
|
||||
"mq_notify": SYS_MQ_NOTIFY,
|
||||
"mq_getsetattr": SYS_MQ_GETSETATTR,
|
||||
"msgget": SYS_MSGGET,
|
||||
"msgctl": SYS_MSGCTL,
|
||||
"msgrcv": SYS_MSGRCV,
|
||||
"msgsnd": SYS_MSGSND,
|
||||
"semget": SYS_SEMGET,
|
||||
"semctl": SYS_SEMCTL,
|
||||
"semtimedop": SYS_SEMTIMEDOP,
|
||||
"semop": SYS_SEMOP,
|
||||
"shmget": SYS_SHMGET,
|
||||
"shmctl": SYS_SHMCTL,
|
||||
"shmat": SYS_SHMAT,
|
||||
"shmdt": SYS_SHMDT,
|
||||
"socket": SYS_SOCKET,
|
||||
"socketpair": SYS_SOCKETPAIR,
|
||||
"bind": SYS_BIND,
|
||||
"listen": SYS_LISTEN,
|
||||
"accept": SYS_ACCEPT,
|
||||
"connect": SYS_CONNECT,
|
||||
"getsockname": SYS_GETSOCKNAME,
|
||||
"getpeername": SYS_GETPEERNAME,
|
||||
"sendto": SYS_SENDTO,
|
||||
"recvfrom": SYS_RECVFROM,
|
||||
"setsockopt": SYS_SETSOCKOPT,
|
||||
"getsockopt": SYS_GETSOCKOPT,
|
||||
"shutdown": SYS_SHUTDOWN,
|
||||
"sendmsg": SYS_SENDMSG,
|
||||
"recvmsg": SYS_RECVMSG,
|
||||
"readahead": SYS_READAHEAD,
|
||||
"brk": SYS_BRK,
|
||||
"munmap": SYS_MUNMAP,
|
||||
"mremap": SYS_MREMAP,
|
||||
"add_key": SYS_ADD_KEY,
|
||||
"request_key": SYS_REQUEST_KEY,
|
||||
"keyctl": SYS_KEYCTL,
|
||||
"clone": SYS_CLONE,
|
||||
"execve": SYS_EXECVE,
|
||||
"mmap": SYS_MMAP,
|
||||
"fadvise64": SYS_FADVISE64,
|
||||
"swapon": SYS_SWAPON,
|
||||
"swapoff": SYS_SWAPOFF,
|
||||
"mprotect": SYS_MPROTECT,
|
||||
"msync": SYS_MSYNC,
|
||||
"mlock": SYS_MLOCK,
|
||||
"munlock": SYS_MUNLOCK,
|
||||
"mlockall": SYS_MLOCKALL,
|
||||
"munlockall": SYS_MUNLOCKALL,
|
||||
"mincore": SYS_MINCORE,
|
||||
"madvise": SYS_MADVISE,
|
||||
"remap_file_pages": SYS_REMAP_FILE_PAGES,
|
||||
"mbind": SYS_MBIND,
|
||||
"get_mempolicy": SYS_GET_MEMPOLICY,
|
||||
"set_mempolicy": SYS_SET_MEMPOLICY,
|
||||
"migrate_pages": SYS_MIGRATE_PAGES,
|
||||
"move_pages": SYS_MOVE_PAGES,
|
||||
"rt_tgsigqueueinfo": SYS_RT_TGSIGQUEUEINFO,
|
||||
"perf_event_open": SYS_PERF_EVENT_OPEN,
|
||||
"accept4": SYS_ACCEPT4,
|
||||
"recvmmsg": SYS_RECVMMSG,
|
||||
"wait4": SYS_WAIT4,
|
||||
"prlimit64": SYS_PRLIMIT64,
|
||||
"fanotify_init": SYS_FANOTIFY_INIT,
|
||||
"fanotify_mark": SYS_FANOTIFY_MARK,
|
||||
"name_to_handle_at": SYS_NAME_TO_HANDLE_AT,
|
||||
"open_by_handle_at": SYS_OPEN_BY_HANDLE_AT,
|
||||
"clock_adjtime": SYS_CLOCK_ADJTIME,
|
||||
"syncfs": SYS_SYNCFS,
|
||||
"setns": SYS_SETNS,
|
||||
"sendmmsg": SYS_SENDMMSG,
|
||||
"process_vm_readv": SYS_PROCESS_VM_READV,
|
||||
"process_vm_writev": SYS_PROCESS_VM_WRITEV,
|
||||
"kcmp": SYS_KCMP,
|
||||
"finit_module": SYS_FINIT_MODULE,
|
||||
"sched_setattr": SYS_SCHED_SETATTR,
|
||||
"sched_getattr": SYS_SCHED_GETATTR,
|
||||
"renameat2": SYS_RENAMEAT2,
|
||||
"seccomp": SYS_SECCOMP,
|
||||
"getrandom": SYS_GETRANDOM,
|
||||
"memfd_create": SYS_MEMFD_CREATE,
|
||||
"bpf": SYS_BPF,
|
||||
"execveat": SYS_EXECVEAT,
|
||||
"userfaultfd": SYS_USERFAULTFD,
|
||||
"membarrier": SYS_MEMBARRIER,
|
||||
"mlock2": SYS_MLOCK2,
|
||||
"copy_file_range": SYS_COPY_FILE_RANGE,
|
||||
"preadv2": SYS_PREADV2,
|
||||
"pwritev2": SYS_PWRITEV2,
|
||||
"pkey_mprotect": SYS_PKEY_MPROTECT,
|
||||
"pkey_alloc": SYS_PKEY_ALLOC,
|
||||
"pkey_free": SYS_PKEY_FREE,
|
||||
"statx": SYS_STATX,
|
||||
"io_pgetevents": SYS_IO_PGETEVENTS,
|
||||
"rseq": SYS_RSEQ,
|
||||
"kexec_file_load": SYS_KEXEC_FILE_LOAD,
|
||||
"pidfd_send_signal": SYS_PIDFD_SEND_SIGNAL,
|
||||
"io_uring_setup": SYS_IO_URING_SETUP,
|
||||
"io_uring_enter": SYS_IO_URING_ENTER,
|
||||
"io_uring_register": SYS_IO_URING_REGISTER,
|
||||
"open_tree": SYS_OPEN_TREE,
|
||||
"move_mount": SYS_MOVE_MOUNT,
|
||||
"fsopen": SYS_FSOPEN,
|
||||
"fsconfig": SYS_FSCONFIG,
|
||||
"fsmount": SYS_FSMOUNT,
|
||||
"fspick": SYS_FSPICK,
|
||||
"pidfd_open": SYS_PIDFD_OPEN,
|
||||
"clone3": SYS_CLONE3,
|
||||
"close_range": SYS_CLOSE_RANGE,
|
||||
"openat2": SYS_OPENAT2,
|
||||
"pidfd_getfd": SYS_PIDFD_GETFD,
|
||||
"faccessat2": SYS_FACCESSAT2,
|
||||
"process_madvise": SYS_PROCESS_MADVISE,
|
||||
"epoll_pwait2": SYS_EPOLL_PWAIT2,
|
||||
"mount_setattr": SYS_MOUNT_SETATTR,
|
||||
"quotactl_fd": SYS_QUOTACTL_FD,
|
||||
"landlock_create_ruleset": SYS_LANDLOCK_CREATE_RULESET,
|
||||
"landlock_add_rule": SYS_LANDLOCK_ADD_RULE,
|
||||
"landlock_restrict_self": SYS_LANDLOCK_RESTRICT_SELF,
|
||||
"memfd_secret": SYS_MEMFD_SECRET,
|
||||
"process_mrelease": SYS_PROCESS_MRELEASE,
|
||||
"futex_waitv": SYS_FUTEX_WAITV,
|
||||
"set_mempolicy_home_node": SYS_SET_MEMPOLICY_HOME_NODE,
|
||||
"cachestat": SYS_CACHESTAT,
|
||||
"fchmodat2": SYS_FCHMODAT2,
|
||||
"map_shadow_stack": SYS_MAP_SHADOW_STACK,
|
||||
"futex_wake": SYS_FUTEX_WAKE,
|
||||
"futex_wait": SYS_FUTEX_WAIT,
|
||||
"futex_requeue": SYS_FUTEX_REQUEUE,
|
||||
"statmount": SYS_STATMOUNT,
|
||||
"listmount": SYS_LISTMOUNT,
|
||||
"lsm_get_self_attr": SYS_LSM_GET_SELF_ATTR,
|
||||
"lsm_set_self_attr": SYS_LSM_SET_SELF_ATTR,
|
||||
"lsm_list_modules": SYS_LSM_LIST_MODULES,
|
||||
"mseal": SYS_MSEAL,
|
||||
}
|
||||
|
||||
const (
|
||||
SYS_USERFAULTFD = 282
|
||||
SYS_MEMBARRIER = 283
|
||||
SYS_MLOCK2 = 284
|
||||
SYS_COPY_FILE_RANGE = 285
|
||||
SYS_PREADV2 = 286
|
||||
SYS_PWRITEV2 = 287
|
||||
SYS_PKEY_MPROTECT = 288
|
||||
SYS_PKEY_ALLOC = 289
|
||||
SYS_PKEY_FREE = 290
|
||||
SYS_STATX = 291
|
||||
SYS_IO_PGETEVENTS = 292
|
||||
SYS_RSEQ = 293
|
||||
SYS_KEXEC_FILE_LOAD = 294
|
||||
SYS_PIDFD_SEND_SIGNAL = 424
|
||||
SYS_IO_URING_SETUP = 425
|
||||
SYS_IO_URING_ENTER = 426
|
||||
SYS_IO_URING_REGISTER = 427
|
||||
SYS_OPEN_TREE = 428
|
||||
SYS_MOVE_MOUNT = 429
|
||||
SYS_FSOPEN = 430
|
||||
SYS_FSCONFIG = 431
|
||||
SYS_FSMOUNT = 432
|
||||
SYS_FSPICK = 433
|
||||
SYS_PIDFD_OPEN = 434
|
||||
SYS_CLONE3 = 435
|
||||
SYS_CLOSE_RANGE = 436
|
||||
SYS_OPENAT2 = 437
|
||||
SYS_PIDFD_GETFD = 438
|
||||
SYS_FACCESSAT2 = 439
|
||||
SYS_PROCESS_MADVISE = 440
|
||||
SYS_EPOLL_PWAIT2 = 441
|
||||
SYS_MOUNT_SETATTR = 442
|
||||
SYS_QUOTACTL_FD = 443
|
||||
SYS_LANDLOCK_CREATE_RULESET = 444
|
||||
SYS_LANDLOCK_ADD_RULE = 445
|
||||
SYS_LANDLOCK_RESTRICT_SELF = 446
|
||||
SYS_MEMFD_SECRET = 447
|
||||
SYS_PROCESS_MRELEASE = 448
|
||||
SYS_FUTEX_WAITV = 449
|
||||
SYS_SET_MEMPOLICY_HOME_NODE = 450
|
||||
SYS_CACHESTAT = 451
|
||||
SYS_FCHMODAT2 = 452
|
||||
SYS_MAP_SHADOW_STACK = 453
|
||||
SYS_FUTEX_WAKE = 454
|
||||
SYS_FUTEX_WAIT = 455
|
||||
SYS_FUTEX_REQUEUE = 456
|
||||
SYS_STATMOUNT = 457
|
||||
SYS_LISTMOUNT = 458
|
||||
SYS_LSM_GET_SELF_ATTR = 459
|
||||
SYS_LSM_SET_SELF_ATTR = 460
|
||||
SYS_LSM_LIST_MODULES = 461
|
||||
SYS_MSEAL = 462
|
||||
)
|
||||
20
container/seccomp/syscall_test.go
Normal file
20
container/seccomp/syscall_test.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package seccomp
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSyscallResolveName(t *testing.T) {
|
||||
for name, want := range Syscalls() {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if got := syscallResolveName(name); got != want {
|
||||
t.Errorf("syscallResolveName(%q) = %d, want %d",
|
||||
name, got, want)
|
||||
}
|
||||
if got, ok := SyscallResolveName(name); !ok || got != want {
|
||||
t.Errorf("SyscallResolveName(%q) = %d, want %d",
|
||||
name, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
35
container/syscall.go
Normal file
35
container/syscall.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
SUID_DUMP_DISABLE = iota
|
||||
SUID_DUMP_USER
|
||||
)
|
||||
|
||||
func SetDumpable(dumpable uintptr) error {
|
||||
// linux/sched/coredump.h
|
||||
if _, _, errno := syscall.Syscall(syscall.SYS_PRCTL, syscall.PR_SET_DUMPABLE, dumpable, 0); errno != 0 {
|
||||
return errno
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IgnoringEINTR makes a function call and repeats it if it returns an
|
||||
// EINTR error. This appears to be required even though we install all
|
||||
// signal handlers with SA_RESTART: see #22838, #38033, #38836, #40846.
|
||||
// Also #20400 and #36644 are issues in which a signal handler is
|
||||
// installed without setting SA_RESTART. None of these are the common case,
|
||||
// but there are enough of them that it seems that we can't avoid
|
||||
// an EINTR loop.
|
||||
func IgnoringEINTR(fn func() error) error {
|
||||
for {
|
||||
err := fn()
|
||||
if err != syscall.EINTR {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
7
container/syscall_amd64.go
Normal file
7
container/syscall_amd64.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package container
|
||||
|
||||
const (
|
||||
O_PATH = 0x200000
|
||||
|
||||
PR_SET_NO_NEW_PRIVS = 0x26
|
||||
)
|
||||
47
container/sysctl.go
Normal file
47
container/sysctl.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
kernelOverflowuid int
|
||||
kernelOverflowgid int
|
||||
kernelCapLastCap int
|
||||
|
||||
sysctlOnce sync.Once
|
||||
)
|
||||
|
||||
const (
|
||||
kernelOverflowuidPath = "/proc/sys/kernel/overflowuid"
|
||||
kernelOverflowgidPath = "/proc/sys/kernel/overflowgid"
|
||||
kernelCapLastCapPath = "/proc/sys/kernel/cap_last_cap"
|
||||
)
|
||||
|
||||
func mustReadSysctl() {
|
||||
if v, err := os.ReadFile(kernelOverflowuidPath); err != nil {
|
||||
log.Fatalf("cannot read %q: %v", kernelOverflowuidPath, err)
|
||||
} else if kernelOverflowuid, err = strconv.Atoi(string(bytes.TrimSpace(v))); err != nil {
|
||||
log.Fatalf("cannot interpret %q: %v", kernelOverflowuidPath, err)
|
||||
}
|
||||
|
||||
if v, err := os.ReadFile(kernelOverflowgidPath); err != nil {
|
||||
log.Fatalf("cannot read %q: %v", kernelOverflowgidPath, err)
|
||||
} else if kernelOverflowgid, err = strconv.Atoi(string(bytes.TrimSpace(v))); err != nil {
|
||||
log.Fatalf("cannot interpret %q: %v", kernelOverflowgidPath, err)
|
||||
}
|
||||
|
||||
if v, err := os.ReadFile(kernelCapLastCapPath); err != nil {
|
||||
log.Fatalf("cannot read %q: %v", kernelCapLastCapPath, err)
|
||||
} else if kernelCapLastCap, err = strconv.Atoi(string(bytes.TrimSpace(v))); err != nil {
|
||||
log.Fatalf("cannot interpret %q: %v", kernelCapLastCapPath, err)
|
||||
}
|
||||
}
|
||||
|
||||
func OverflowUid() int { sysctlOnce.Do(mustReadSysctl); return kernelOverflowuid }
|
||||
func OverflowGid() int { sysctlOnce.Do(mustReadSysctl); return kernelOverflowgid }
|
||||
func LastCap() uintptr { sysctlOnce.Do(mustReadSysctl); return uintptr(kernelCapLastCap) }
|
||||
30
container/vfs/mangle.go
Normal file
30
container/vfs/mangle.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package vfs
|
||||
|
||||
import "strings"
|
||||
|
||||
func Unmangle(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
|
||||
v := make([]byte, len(s))
|
||||
var (
|
||||
j int
|
||||
c byte
|
||||
)
|
||||
for i := 0; i < len(s); i++ {
|
||||
c = s[i]
|
||||
if c == '\\' && len(s) > i+3 &&
|
||||
(s[i+1] == '0' || s[i+1] == '1') &&
|
||||
(s[i+2] >= '0' && s[i+2] <= '7') &&
|
||||
(s[i+3] >= '0' && s[i+3] <= '7') {
|
||||
c = ((s[i+1] - '0') << 6) |
|
||||
((s[i+2] - '0') << 3) |
|
||||
(s[i+3] - '0')
|
||||
i += 3
|
||||
}
|
||||
v[j] = c
|
||||
j++
|
||||
}
|
||||
return string(v[:j])
|
||||
}
|
||||
27
container/vfs/mangle_test.go
Normal file
27
container/vfs/mangle_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package vfs_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container/vfs"
|
||||
)
|
||||
|
||||
func TestUnmangle(t *testing.T) {
|
||||
testCases := []struct {
|
||||
want string
|
||||
sample string
|
||||
}{
|
||||
{`\, `, `\134\054\040`},
|
||||
{`(10) source -- maybe empty string`, `(10)\040source\040--\040maybe empty string`},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.want, func(t *testing.T) {
|
||||
got := vfs.Unmangle(tc.sample)
|
||||
if got != tc.want {
|
||||
t.Errorf("Unmangle: %q, want %q",
|
||||
got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
260
container/vfs/mountinfo.go
Normal file
260
container/vfs/mountinfo.go
Normal file
@@ -0,0 +1,260 @@
|
||||
// Package vfs provides bindings and iterators over proc_pid_mountinfo(5).
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
MS_NOSYMFOLLOW = 0x100
|
||||
)
|
||||
|
||||
var (
|
||||
ErrMountInfoFields = errors.New("unexpected field count")
|
||||
ErrMountInfoEmpty = errors.New("unexpected empty field")
|
||||
ErrMountInfoDevno = errors.New("bad maj:min field")
|
||||
ErrMountInfoSep = errors.New("bad optional fields separator")
|
||||
)
|
||||
|
||||
type (
|
||||
// A MountInfoDecoder reads and decodes proc_pid_mountinfo(5) entries from an input stream.
|
||||
MountInfoDecoder struct {
|
||||
s *bufio.Scanner
|
||||
m *MountInfo
|
||||
|
||||
current *MountInfo
|
||||
parseErr error
|
||||
complete bool
|
||||
}
|
||||
|
||||
// MountInfo represents the contents of a proc_pid_mountinfo(5) document.
|
||||
MountInfo struct {
|
||||
Next *MountInfo
|
||||
MountInfoEntry
|
||||
}
|
||||
|
||||
// MountInfoEntry represents a proc_pid_mountinfo(5) entry.
|
||||
MountInfoEntry struct {
|
||||
// mount ID: a unique ID for the mount (may be reused after umount(2)).
|
||||
ID int `json:"id"`
|
||||
// parent ID: the ID of the parent mount (or of self for the root of this mount namespace's mount tree).
|
||||
Parent int `json:"parent"`
|
||||
// major:minor: the value of st_dev for files on this filesystem (see stat(2)).
|
||||
Devno DevT `json:"devno"`
|
||||
// root: the pathname of the directory in the filesystem which forms the root of this mount.
|
||||
Root string `json:"root"`
|
||||
// mount point: the pathname of the mount point relative to the process's root directory.
|
||||
Target string `json:"target"`
|
||||
// mount options: per-mount options (see mount(2)).
|
||||
VfsOptstr string `json:"vfs_optstr"`
|
||||
// optional fields: zero or more fields of the form "tag[:value]"; see below.
|
||||
// separator: the end of the optional fields is marked by a single hyphen.
|
||||
OptFields []string `json:"opt_fields"`
|
||||
// filesystem type: the filesystem type in the form "type[.subtype]".
|
||||
FsType string `json:"fstype"`
|
||||
// mount source: filesystem-specific information or "none".
|
||||
Source string `json:"source"`
|
||||
// super options: per-superblock options (see mount(2)).
|
||||
FsOptstr string `json:"fs_optstr"`
|
||||
}
|
||||
|
||||
DevT [2]int
|
||||
)
|
||||
|
||||
// Flags interprets VfsOptstr and returns the resulting flags and unmatched options.
|
||||
func (e *MountInfoEntry) Flags() (flags uintptr, unmatched []string) {
|
||||
for _, s := range strings.Split(e.VfsOptstr, ",") {
|
||||
switch s {
|
||||
case "rw":
|
||||
case "ro":
|
||||
flags |= syscall.MS_RDONLY
|
||||
case "nosuid":
|
||||
flags |= syscall.MS_NOSUID
|
||||
case "nodev":
|
||||
flags |= syscall.MS_NODEV
|
||||
case "noexec":
|
||||
flags |= syscall.MS_NOEXEC
|
||||
case "nosymfollow":
|
||||
flags |= MS_NOSYMFOLLOW
|
||||
case "noatime":
|
||||
flags |= syscall.MS_NOATIME
|
||||
case "nodiratime":
|
||||
flags |= syscall.MS_NODIRATIME
|
||||
case "relatime":
|
||||
flags |= syscall.MS_RELATIME
|
||||
default:
|
||||
unmatched = append(unmatched, s)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// NewMountInfoDecoder returns a new decoder that reads from r.
|
||||
//
|
||||
// The decoder introduces its own buffering and may read data from r beyond the mountinfo entries requested.
|
||||
func NewMountInfoDecoder(r io.Reader) *MountInfoDecoder {
|
||||
return &MountInfoDecoder{s: bufio.NewScanner(r)}
|
||||
}
|
||||
|
||||
func (d *MountInfoDecoder) Decode(v **MountInfo) (err error) {
|
||||
for d.scan() {
|
||||
}
|
||||
err = d.Err()
|
||||
if err == nil {
|
||||
*v = d.m
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Entries returns an iterator over mountinfo entries.
|
||||
func (d *MountInfoDecoder) Entries() iter.Seq[*MountInfoEntry] {
|
||||
return func(yield func(*MountInfoEntry) bool) {
|
||||
for cur := d.m; cur != nil; cur = cur.Next {
|
||||
if !yield(&cur.MountInfoEntry) {
|
||||
return
|
||||
}
|
||||
}
|
||||
for d.scan() {
|
||||
if !yield(&d.current.MountInfoEntry) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *MountInfoDecoder) Err() error {
|
||||
if err := d.s.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.parseErr
|
||||
}
|
||||
|
||||
func (d *MountInfoDecoder) scan() bool {
|
||||
if d.complete {
|
||||
return false
|
||||
}
|
||||
if !d.s.Scan() {
|
||||
d.complete = true
|
||||
return false
|
||||
}
|
||||
|
||||
m := new(MountInfo)
|
||||
if err := parseMountInfoLine(d.s.Text(), &m.MountInfoEntry); err != nil {
|
||||
d.parseErr = err
|
||||
d.complete = true
|
||||
return false
|
||||
}
|
||||
|
||||
if d.current == nil {
|
||||
d.m = m
|
||||
d.current = d.m
|
||||
} else {
|
||||
d.current.Next = m
|
||||
d.current = d.current.Next
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func parseMountInfoLine(s string, ent *MountInfoEntry) error {
|
||||
// prevent proceeding with misaligned fields due to optional fields
|
||||
f := strings.Split(s, " ")
|
||||
if len(f) < 10 {
|
||||
return ErrMountInfoFields
|
||||
}
|
||||
|
||||
// 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
|
||||
// (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
|
||||
|
||||
// (1) id
|
||||
if id, err := strconv.Atoi(f[0]); err != nil { // 0
|
||||
return err
|
||||
} else {
|
||||
ent.ID = id
|
||||
}
|
||||
|
||||
// (2) parent
|
||||
if parent, err := strconv.Atoi(f[1]); err != nil { // 1
|
||||
return err
|
||||
} else {
|
||||
ent.Parent = parent
|
||||
}
|
||||
|
||||
// (3) maj:min
|
||||
if n, err := fmt.Sscanf(f[2], "%d:%d", &ent.Devno[0], &ent.Devno[1]); err != nil {
|
||||
return err
|
||||
} else if n != 2 {
|
||||
// unreachable
|
||||
return ErrMountInfoDevno
|
||||
}
|
||||
|
||||
// (4) mountroot
|
||||
ent.Root = Unmangle(f[3])
|
||||
if ent.Root == "" {
|
||||
return ErrMountInfoEmpty
|
||||
}
|
||||
|
||||
// (5) target
|
||||
ent.Target = Unmangle(f[4])
|
||||
if ent.Target == "" {
|
||||
return ErrMountInfoEmpty
|
||||
}
|
||||
|
||||
// (6) vfs options (fs-independent)
|
||||
ent.VfsOptstr = Unmangle(f[5])
|
||||
if ent.VfsOptstr == "" {
|
||||
return ErrMountInfoEmpty
|
||||
}
|
||||
|
||||
// (7) optional fields, terminated by " - "
|
||||
i := len(f) - 4
|
||||
ent.OptFields = f[6:i]
|
||||
|
||||
// (8) optional fields end marker
|
||||
if f[i] != "-" {
|
||||
return ErrMountInfoSep
|
||||
}
|
||||
i++
|
||||
|
||||
// (9) FS type
|
||||
ent.FsType = Unmangle(f[i])
|
||||
if ent.FsType == "" {
|
||||
return ErrMountInfoEmpty
|
||||
}
|
||||
i++
|
||||
|
||||
// (10) source -- maybe empty string
|
||||
ent.Source = Unmangle(f[i])
|
||||
i++
|
||||
|
||||
// (11) fs options (fs specific)
|
||||
ent.FsOptstr = Unmangle(f[i])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *MountInfoEntry) EqualWithIgnore(want *MountInfoEntry, ignore string) bool {
|
||||
return (e.ID == want.ID || want.ID == -1) &&
|
||||
(e.Parent == want.Parent || want.Parent == -1) &&
|
||||
(e.Devno == want.Devno || (want.Devno[0] == -1 && want.Devno[1] == -1)) &&
|
||||
(e.Root == want.Root || want.Root == ignore) &&
|
||||
(e.Target == want.Target || want.Target == ignore) &&
|
||||
(e.VfsOptstr == want.VfsOptstr || want.VfsOptstr == ignore) &&
|
||||
(slices.Equal(e.OptFields, want.OptFields) || (len(want.OptFields) == 1 && want.OptFields[0] == ignore)) &&
|
||||
(e.FsType == want.FsType || want.FsType == ignore) &&
|
||||
(e.Source == want.Source || want.Source == ignore) &&
|
||||
(e.FsOptstr == want.FsOptstr || want.FsOptstr == ignore)
|
||||
}
|
||||
|
||||
func (e *MountInfoEntry) String() string {
|
||||
return fmt.Sprintf("%d %d %d:%d %s %s %s %s %s %s %s",
|
||||
e.ID, e.Parent, e.Devno[0], e.Devno[1], e.Root, e.Target, e.VfsOptstr,
|
||||
strings.Join(append(e.OptFields, "-"), " "), e.FsType, e.Source, e.FsOptstr)
|
||||
}
|
||||
404
container/vfs/mountinfo_test.go
Normal file
404
container/vfs/mountinfo_test.go
Normal file
@@ -0,0 +1,404 @@
|
||||
package vfs_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"iter"
|
||||
"path"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container/vfs"
|
||||
)
|
||||
|
||||
func TestMountInfo(t *testing.T) {
|
||||
testCases := []mountInfoTest{
|
||||
{"count", sampleMountinfoBase + `
|
||||
21 20 0:53/ /mnt/test rw,relatime - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoFields, "", nil, nil, nil},
|
||||
|
||||
{"sep", sampleMountinfoBase + `
|
||||
21 20 0:53 / /mnt/test rw,relatime shared:212 _ tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoSep, "", nil, nil, nil},
|
||||
|
||||
{"id", sampleMountinfoBase + `
|
||||
id 20 0:53 / /mnt/test rw,relatime shared:212 - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
strconv.ErrSyntax, "", nil, nil, nil},
|
||||
|
||||
{"parent", sampleMountinfoBase + `
|
||||
21 parent 0:53 / /mnt/test rw,relatime shared:212 - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
strconv.ErrSyntax, "", nil, nil, nil},
|
||||
|
||||
{"devno", sampleMountinfoBase + `
|
||||
21 20 053 / /mnt/test rw,relatime shared:212 - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
nil, "unexpected EOF", nil, nil, nil},
|
||||
|
||||
{"maj", sampleMountinfoBase + `
|
||||
21 20 maj:53 / /mnt/test rw,relatime shared:212 - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
nil, "expected integer", nil, nil, nil},
|
||||
|
||||
{"min", sampleMountinfoBase + `
|
||||
21 20 0:min / /mnt/test rw,relatime shared:212 - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
nil, "expected integer", nil, nil, nil},
|
||||
|
||||
{"mountroot", sampleMountinfoBase + `
|
||||
21 20 0:53 /mnt/test rw,relatime - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoEmpty, "", nil, nil, nil},
|
||||
|
||||
{"target", sampleMountinfoBase + `
|
||||
21 20 0:53 / rw,relatime - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoEmpty, "", nil, nil, nil},
|
||||
|
||||
{"vfs options", sampleMountinfoBase + `
|
||||
21 20 0:53 / /mnt/test - tmpfs rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoEmpty, "", nil, nil, nil},
|
||||
|
||||
{"FS type", sampleMountinfoBase + `
|
||||
21 20 0:53 / /mnt/test rw,relatime - rw
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755`,
|
||||
vfs.ErrMountInfoEmpty, "", nil, nil, nil},
|
||||
|
||||
{"base", sampleMountinfoBase, nil, "", []*wantMountInfo{
|
||||
m(15, 20, 0, 3, "/", "/proc", "rw,relatime", o(), "proc", "/proc", "rw", syscall.MS_RELATIME, nil),
|
||||
m(16, 20, 0, 15, "/", "/sys", "rw,relatime", o(), "sysfs", "/sys", "rw", syscall.MS_RELATIME, nil),
|
||||
m(17, 20, 0, 5, "/", "/dev", "rw,relatime", o(), "devtmpfs", "udev", "rw,size=1983516k,nr_inodes=495879,mode=755", syscall.MS_RELATIME, nil),
|
||||
m(18, 17, 0, 10, "/", "/dev/pts", "rw,relatime", o(), "devpts", "devpts", "rw,gid=5,mode=620,ptmxmode=000", syscall.MS_RELATIME, nil),
|
||||
m(19, 17, 0, 16, "/", "/dev/shm", "rw,relatime", o(), "tmpfs", "tmpfs", "rw", syscall.MS_RELATIME, nil),
|
||||
m(20, 1, 8, 4, "/", "/", "ro,noatime,nodiratime,meow", o(), "ext3", "/dev/sda4", "rw,errors=continue,user_xattr,acl,barrier=0,data=ordered", syscall.MS_RDONLY|syscall.MS_NOATIME|syscall.MS_NODIRATIME, []string{"meow"}),
|
||||
},
|
||||
mn(20, 1, 8, 4, "/", "/", "ro,noatime,nodiratime,meow", o(), "ext3", "/dev/sda4", "rw,errors=continue,user_xattr,acl,barrier=0,data=ordered", false,
|
||||
mn(15, 20, 0, 3, "/", "/proc", "rw,relatime", o(), "proc", "/proc", "rw", false, nil,
|
||||
mn(16, 20, 0, 15, "/", "/sys", "rw,relatime", o(), "sysfs", "/sys", "rw", false, nil,
|
||||
mn(17, 20, 0, 5, "/", "/dev", "rw,relatime", o(), "devtmpfs", "udev", "rw,size=1983516k,nr_inodes=495879,mode=755", false,
|
||||
mn(18, 17, 0, 10, "/", "/dev/pts", "rw,relatime", o(), "devpts", "devpts", "rw,gid=5,mode=620,ptmxmode=000", false, nil,
|
||||
mn(19, 17, 0, 16, "/", "/dev/shm", "rw,relatime", o(), "tmpfs", "tmpfs", "rw", false, nil, nil)),
|
||||
nil))), nil), func(n *vfs.MountInfoNode) []*vfs.MountInfoNode {
|
||||
return []*vfs.MountInfoNode{
|
||||
n,
|
||||
n.FirstChild,
|
||||
n.FirstChild.NextSibling,
|
||||
n.FirstChild.NextSibling.NextSibling,
|
||||
n.FirstChild.NextSibling.NextSibling.FirstChild,
|
||||
n.FirstChild.NextSibling.NextSibling.FirstChild.NextSibling,
|
||||
}
|
||||
}},
|
||||
|
||||
{"sample", sampleMountinfo, nil, "", []*wantMountInfo{
|
||||
m(15, 20, 0, 3, "/", "/proc", "rw,relatime", o(), "proc", "/proc", "rw", syscall.MS_RELATIME, nil),
|
||||
m(16, 20, 0, 15, "/", "/sys", "rw,relatime", o(), "sysfs", "/sys", "rw", syscall.MS_RELATIME, nil),
|
||||
m(17, 20, 0, 5, "/", "/dev", "rw,relatime", o(), "devtmpfs", "udev", "rw,size=1983516k,nr_inodes=495879,mode=755", syscall.MS_RELATIME, nil),
|
||||
m(18, 17, 0, 10, "/", "/dev/pts", "rw,relatime", o(), "devpts", "devpts", "rw,gid=5,mode=620,ptmxmode=000", syscall.MS_RELATIME, nil),
|
||||
m(19, 17, 0, 16, "/", "/dev/shm", "rw,relatime", o(), "tmpfs", "tmpfs", "rw", syscall.MS_RELATIME, nil),
|
||||
m(20, 1, 8, 4, "/", "/", "rw,noatime", o(), "ext3", "/dev/sda4", "rw,errors=continue,user_xattr,acl,barrier=0,data=ordered", syscall.MS_NOATIME, nil),
|
||||
m(21, 16, 0, 17, "/", "/sys/fs/cgroup", "rw,nosuid,nodev,noexec,relatime", o(), "tmpfs", "tmpfs", "rw,mode=755", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(22, 21, 0, 18, "/", "/sys/fs/cgroup/systemd", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(23, 21, 0, 19, "/", "/sys/fs/cgroup/cpuset", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,cpuset", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(24, 21, 0, 20, "/", "/sys/fs/cgroup/ns", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,ns", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(25, 21, 0, 21, "/", "/sys/fs/cgroup/cpu", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,cpu", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(26, 21, 0, 22, "/", "/sys/fs/cgroup/cpuacct", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,cpuacct", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(27, 21, 0, 23, "/", "/sys/fs/cgroup/memory", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,memory", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(28, 21, 0, 24, "/", "/sys/fs/cgroup/devices", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,devices", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(29, 21, 0, 25, "/", "/sys/fs/cgroup/freezer", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,freezer", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(30, 21, 0, 26, "/", "/sys/fs/cgroup/net_cls", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,net_cls", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(31, 21, 0, 27, "/", "/sys/fs/cgroup/blkio", "rw,nosuid,nodev,noexec,relatime", o(), "cgroup", "cgroup", "rw,blkio", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_NOEXEC|syscall.MS_RELATIME, nil),
|
||||
m(32, 16, 0, 28, "/", "/sys/kernel/security", "rw,relatime", o(), "autofs", "systemd-1", "rw,fd=22,pgrp=1,timeout=300,minproto=5,maxproto=5,direct", syscall.MS_RELATIME, nil),
|
||||
m(33, 17, 0, 29, "/", "/dev/hugepages", "rw,relatime", o(), "autofs", "systemd-1", "rw,fd=23,pgrp=1,timeout=300,minproto=5,maxproto=5,direct", syscall.MS_RELATIME, nil),
|
||||
m(34, 16, 0, 30, "/", "/sys/kernel/debug", "rw,relatime", o(), "autofs", "systemd-1", "rw,fd=24,pgrp=1,timeout=300,minproto=5,maxproto=5,direct", syscall.MS_RELATIME, nil),
|
||||
m(35, 15, 0, 31, "/", "/proc/sys/fs/binfmt_misc", "rw,relatime", o(), "autofs", "systemd-1", "rw,fd=25,pgrp=1,timeout=300,minproto=5,maxproto=5,direct", syscall.MS_RELATIME, nil),
|
||||
m(36, 17, 0, 32, "/", "/dev/mqueue", "rw,relatime", o(), "autofs", "systemd-1", "rw,fd=26,pgrp=1,timeout=300,minproto=5,maxproto=5,direct", syscall.MS_RELATIME, nil),
|
||||
m(37, 15, 0, 14, "/", "/proc/bus/usb", "rw,relatime", o(), "usbfs", "/proc/bus/usb", "rw", syscall.MS_RELATIME, nil),
|
||||
m(38, 33, 0, 33, "/", "/dev/hugepages", "rw,relatime", o(), "hugetlbfs", "hugetlbfs", "rw", syscall.MS_RELATIME, nil),
|
||||
m(39, 36, 0, 12, "/", "/dev/mqueue", "rw,relatime", o(), "mqueue", "mqueue", "rw", syscall.MS_RELATIME, nil),
|
||||
m(40, 20, 8, 6, "/", "/boot", "rw,noatime", o(), "ext3", "/dev/sda6", "rw,errors=continue,barrier=0,data=ordered", syscall.MS_NOATIME, nil),
|
||||
m(41, 20, 253, 0, "/", "/home/kzak", "rw,noatime", o(), "ext4", "/dev/mapper/kzak-home", "rw,barrier=1,data=ordered", syscall.MS_NOATIME, nil),
|
||||
m(42, 35, 0, 34, "/", "/proc/sys/fs/binfmt_misc", "rw,relatime", o(), "binfmt_misc", "none", "rw", syscall.MS_RELATIME, nil),
|
||||
m(43, 16, 0, 35, "/", "/sys/fs/fuse/connections", "rw,relatime", o(), "fusectl", "fusectl", "rw", syscall.MS_RELATIME, nil),
|
||||
m(44, 41, 0, 36, "/", "/home/kzak/.gvfs", "rw,nosuid,nodev,relatime", o(), "fuse.gvfs-fuse-daemon", "gvfs-fuse-daemon", "rw,user_id=500,group_id=500", syscall.MS_NOSUID|syscall.MS_NODEV|syscall.MS_RELATIME, nil),
|
||||
m(45, 20, 0, 37, "/", "/var/lib/nfs/rpc_pipefs", "rw,relatime", o(), "rpc_pipefs", "sunrpc", "rw", syscall.MS_RELATIME, nil),
|
||||
m(47, 20, 0, 38, "/", "/mnt/sounds", "rw,relatime", o(), "cifs", "//foo.home/bar/", "rw,unc=\\\\foo.home\\bar,username=kzak,domain=SRGROUP,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.111.1,posixpaths,serverino,acl,rsize=16384,wsize=57344", syscall.MS_RELATIME, nil),
|
||||
m(49, 20, 0, 56, "/", "/mnt/test/foobar", "rw,relatime,nosymfollow", o("shared:323"), "tmpfs", "tmpfs", "rw", syscall.MS_RELATIME|vfs.MS_NOSYMFOLLOW, nil),
|
||||
}, nil, nil},
|
||||
|
||||
{"sample nosrc", sampleMountinfoNoSrc, nil, "", []*wantMountInfo{
|
||||
m(15, 20, 0, 3, "/", "/proc", "rw,relatime", o(), "proc", "/proc", "rw", syscall.MS_RELATIME, nil),
|
||||
m(16, 20, 0, 15, "/", "/sys", "rw,relatime", o(), "sysfs", "/sys", "rw", syscall.MS_RELATIME, nil),
|
||||
m(17, 20, 0, 5, "/", "/dev", "rw,relatime", o(), "devtmpfs", "udev", "rw,size=1983516k,nr_inodes=495879,mode=755", syscall.MS_RELATIME, nil),
|
||||
m(18, 17, 0, 10, "/", "/dev/pts", "rw,relatime", o(), "devpts", "devpts", "rw,gid=5,mode=620,ptmxmode=000", syscall.MS_RELATIME, nil),
|
||||
m(19, 17, 0, 16, "/", "/dev/shm", "rw,relatime", o(), "tmpfs", "tmpfs", "rw", syscall.MS_RELATIME, nil),
|
||||
m(20, 1, 8, 4, "/", "/", "rw,noatime", o(), "ext3", "/dev/sda4", "rw,errors=continue,user_xattr,acl,barrier=0,data=ordered", syscall.MS_NOATIME, nil),
|
||||
m(21, 20, 0, 53, "/", "/mnt/test", "rw,relatime", o("shared:212"), "tmpfs", "", "rw", syscall.MS_RELATIME, nil),
|
||||
}, nil, nil},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Run("decode", func(t *testing.T) {
|
||||
var got *vfs.MountInfo
|
||||
d := vfs.NewMountInfoDecoder(strings.NewReader(tc.sample))
|
||||
err := d.Decode(&got)
|
||||
tc.check(t, d, "Decode",
|
||||
func(yield func(*vfs.MountInfoEntry) bool) {
|
||||
for cur := got; cur != nil; cur = cur.Next {
|
||||
if !yield(&cur.MountInfoEntry) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}, func() error { return err })
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
tc.check(t, d, "Entries",
|
||||
d.Entries(), d.Err)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("iter", func(t *testing.T) {
|
||||
d := vfs.NewMountInfoDecoder(strings.NewReader(tc.sample))
|
||||
tc.check(t, d, "Entries",
|
||||
d.Entries(), d.Err)
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
tc.check(t, d, "Entries",
|
||||
d.Entries(), d.Err)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("yield", func(t *testing.T) {
|
||||
d := vfs.NewMountInfoDecoder(strings.NewReader(tc.sample))
|
||||
v := false
|
||||
d.Entries()(func(entry *vfs.MountInfoEntry) bool { v = !v; return v })
|
||||
d.Entries()(func(entry *vfs.MountInfoEntry) bool { return false })
|
||||
|
||||
tc.check(t, d, "Entries",
|
||||
d.Entries(), d.Err)
|
||||
|
||||
t.Run("reuse", func(t *testing.T) {
|
||||
tc.check(t, d, "Entries",
|
||||
d.Entries(), d.Err)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type mountInfoTest struct {
|
||||
name string
|
||||
sample string
|
||||
wantErr error
|
||||
wantError string
|
||||
want []*wantMountInfo
|
||||
|
||||
wantNode *vfs.MountInfoNode
|
||||
wantCollectF func(n *vfs.MountInfoNode) []*vfs.MountInfoNode
|
||||
}
|
||||
|
||||
func (tc *mountInfoTest) check(t *testing.T, d *vfs.MountInfoDecoder, funcName string,
|
||||
got iter.Seq[*vfs.MountInfoEntry], gotErr func() error) {
|
||||
i := 0
|
||||
for cur := range got {
|
||||
if i == len(tc.want) {
|
||||
if funcName != "Decode" && (tc.wantErr != nil || tc.wantError != "") {
|
||||
continue
|
||||
}
|
||||
|
||||
t.Errorf("%s: got more than %d entries", funcName, len(tc.want))
|
||||
break
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(cur, &tc.want[i].MountInfoEntry) {
|
||||
t.Errorf("%s: entry %d\ngot: %#v\nwant: %#v",
|
||||
funcName, i, cur, tc.want[i])
|
||||
}
|
||||
|
||||
flags, unmatched := cur.Flags()
|
||||
if flags != tc.want[i].flags {
|
||||
t.Errorf("Flags(%q): %#x, want %#x",
|
||||
cur.VfsOptstr, flags, tc.want[i].flags)
|
||||
}
|
||||
if !slices.Equal(unmatched, tc.want[i].unmatched) {
|
||||
t.Errorf("Flags(%q): unmatched = %#q, want %#q",
|
||||
cur.VfsOptstr, unmatched, tc.want[i].unmatched)
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
|
||||
if i != len(tc.want) {
|
||||
t.Errorf("%s: got %d entries, want %d", funcName, i, len(tc.want))
|
||||
}
|
||||
|
||||
if tc.wantErr == nil && tc.wantError == "" && tc.wantCollectF != nil {
|
||||
t.Run("unfold", func(t *testing.T) {
|
||||
n, err := d.Unfold("/")
|
||||
if err != nil {
|
||||
t.Errorf("Unfold: error = %v", err)
|
||||
} else {
|
||||
t.Run("stop", func(t *testing.T) {
|
||||
v := false
|
||||
n.Collective()(func(node *vfs.MountInfoNode) bool { v = !v; return v })
|
||||
})
|
||||
|
||||
if !reflect.DeepEqual(n, tc.wantNode) {
|
||||
t.Errorf("Unfold: %s, want %s",
|
||||
mustMarshal(n), mustMarshal(tc.wantNode))
|
||||
}
|
||||
|
||||
t.Run("collective", func(t *testing.T) {
|
||||
wantCollect := tc.wantCollectF(n)
|
||||
if gotCollect := slices.Collect(n.Collective()); !reflect.DeepEqual(gotCollect, wantCollect) {
|
||||
t.Errorf("Collective: \ngot %#v\nwant %#v",
|
||||
gotCollect, wantCollect)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
} else if tc.wantNode != nil || tc.wantCollectF != nil {
|
||||
panic("invalid test case")
|
||||
} else if _, err := d.Unfold("/"); !errors.Is(err, tc.wantErr) {
|
||||
if tc.wantError == "" {
|
||||
t.Errorf("Unfold: error = %v, wantErr %v",
|
||||
err, tc.wantErr)
|
||||
} else if err != nil && err.Error() != tc.wantError {
|
||||
t.Errorf("Unfold: error = %q, wantError %q",
|
||||
err, tc.wantError)
|
||||
}
|
||||
}
|
||||
|
||||
if err := gotErr(); !errors.Is(err, tc.wantErr) {
|
||||
if tc.wantError == "" {
|
||||
t.Errorf("%s: error = %v, wantErr %v",
|
||||
funcName, err, tc.wantErr)
|
||||
} else if err != nil && err.Error() != tc.wantError {
|
||||
t.Errorf("%s: error = %q, wantError %q",
|
||||
funcName, err, tc.wantError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mustMarshal(v any) string {
|
||||
p, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
return string(p)
|
||||
}
|
||||
|
||||
type wantMountInfo struct {
|
||||
vfs.MountInfoEntry
|
||||
flags uintptr
|
||||
unmatched []string
|
||||
}
|
||||
|
||||
func m(
|
||||
id, parent, maj, min int, root, target, vfsOptstr string, optFields []string, fsType, source, fsOptstr string,
|
||||
flags uintptr, unmatched []string,
|
||||
) *wantMountInfo {
|
||||
return &wantMountInfo{
|
||||
vfs.MountInfoEntry{
|
||||
ID: id,
|
||||
Parent: parent,
|
||||
Devno: vfs.DevT{maj, min},
|
||||
Root: root,
|
||||
Target: target,
|
||||
VfsOptstr: vfsOptstr,
|
||||
OptFields: optFields,
|
||||
FsType: fsType,
|
||||
Source: source,
|
||||
FsOptstr: fsOptstr,
|
||||
}, flags, unmatched,
|
||||
}
|
||||
}
|
||||
|
||||
func mn(
|
||||
id, parent, maj, min int, root, target, vfsOptstr string, optFields []string, fsType, source, fsOptstr string,
|
||||
covered bool, firstChild, nextSibling *vfs.MountInfoNode,
|
||||
) *vfs.MountInfoNode {
|
||||
return &vfs.MountInfoNode{
|
||||
MountInfoEntry: &vfs.MountInfoEntry{
|
||||
ID: id,
|
||||
Parent: parent,
|
||||
Devno: vfs.DevT{maj, min},
|
||||
Root: root,
|
||||
Target: target,
|
||||
VfsOptstr: vfsOptstr,
|
||||
OptFields: optFields,
|
||||
FsType: fsType,
|
||||
Source: source,
|
||||
FsOptstr: fsOptstr,
|
||||
},
|
||||
FirstChild: firstChild,
|
||||
NextSibling: nextSibling,
|
||||
Clean: path.Clean(target),
|
||||
Covered: covered,
|
||||
}
|
||||
}
|
||||
|
||||
func o(field ...string) []string {
|
||||
if field == nil {
|
||||
return []string{}
|
||||
}
|
||||
return field
|
||||
}
|
||||
|
||||
const (
|
||||
sampleMountinfoBase = `15 20 0:3 / /proc rw,relatime - proc /proc rw
|
||||
16 20 0:15 / /sys rw,relatime - sysfs /sys rw
|
||||
17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1983516k,nr_inodes=495879,mode=755
|
||||
18 17 0:10 / /dev/pts rw,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000
|
||||
19 17 0:16 / /dev/shm rw,relatime - tmpfs tmpfs rw
|
||||
20 1 8:4 / / ro,noatime,nodiratime,meow - ext3 /dev/sda4 rw,errors=continue,user_xattr,acl,barrier=0,data=ordered`
|
||||
|
||||
sampleMountinfo = `15 20 0:3 / /proc rw,relatime - proc /proc rw
|
||||
16 20 0:15 / /sys rw,relatime - sysfs /sys rw
|
||||
17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1983516k,nr_inodes=495879,mode=755
|
||||
18 17 0:10 / /dev/pts rw,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000
|
||||
19 17 0:16 / /dev/shm rw,relatime - tmpfs tmpfs rw
|
||||
20 1 8:4 / / rw,noatime - ext3 /dev/sda4 rw,errors=continue,user_xattr,acl,barrier=0,data=ordered
|
||||
21 16 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755
|
||||
22 21 0:18 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd
|
||||
23 21 0:19 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuset
|
||||
24 21 0:20 / /sys/fs/cgroup/ns rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,ns
|
||||
25 21 0:21 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpu
|
||||
26 21 0:22 / /sys/fs/cgroup/cpuacct rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuacct
|
||||
27 21 0:23 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory
|
||||
28 21 0:24 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,devices
|
||||
29 21 0:25 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,freezer
|
||||
30 21 0:26 / /sys/fs/cgroup/net_cls rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,net_cls
|
||||
31 21 0:27 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,blkio
|
||||
32 16 0:28 / /sys/kernel/security rw,relatime - autofs systemd-1 rw,fd=22,pgrp=1,timeout=300,minproto=5,maxproto=5,direct
|
||||
33 17 0:29 / /dev/hugepages rw,relatime - autofs systemd-1 rw,fd=23,pgrp=1,timeout=300,minproto=5,maxproto=5,direct
|
||||
34 16 0:30 / /sys/kernel/debug rw,relatime - autofs systemd-1 rw,fd=24,pgrp=1,timeout=300,minproto=5,maxproto=5,direct
|
||||
35 15 0:31 / /proc/sys/fs/binfmt_misc rw,relatime - autofs systemd-1 rw,fd=25,pgrp=1,timeout=300,minproto=5,maxproto=5,direct
|
||||
36 17 0:32 / /dev/mqueue rw,relatime - autofs systemd-1 rw,fd=26,pgrp=1,timeout=300,minproto=5,maxproto=5,direct
|
||||
37 15 0:14 / /proc/bus/usb rw,relatime - usbfs /proc/bus/usb rw
|
||||
38 33 0:33 / /dev/hugepages rw,relatime - hugetlbfs hugetlbfs rw
|
||||
39 36 0:12 / /dev/mqueue rw,relatime - mqueue mqueue rw
|
||||
40 20 8:6 / /boot rw,noatime - ext3 /dev/sda6 rw,errors=continue,barrier=0,data=ordered
|
||||
41 20 253:0 / /home/kzak rw,noatime - ext4 /dev/mapper/kzak-home rw,barrier=1,data=ordered
|
||||
42 35 0:34 / /proc/sys/fs/binfmt_misc rw,relatime - binfmt_misc none rw
|
||||
43 16 0:35 / /sys/fs/fuse/connections rw,relatime - fusectl fusectl rw
|
||||
44 41 0:36 / /home/kzak/.gvfs rw,nosuid,nodev,relatime - fuse.gvfs-fuse-daemon gvfs-fuse-daemon rw,user_id=500,group_id=500
|
||||
45 20 0:37 / /var/lib/nfs/rpc_pipefs rw,relatime - rpc_pipefs sunrpc rw
|
||||
47 20 0:38 / /mnt/sounds rw,relatime - cifs //foo.home/bar/ rw,unc=\\foo.home\bar,username=kzak,domain=SRGROUP,uid=0,noforceuid,gid=0,noforcegid,addr=192.168.111.1,posixpaths,serverino,acl,rsize=16384,wsize=57344
|
||||
49 20 0:56 / /mnt/test/foobar rw,relatime,nosymfollow shared:323 - tmpfs tmpfs rw`
|
||||
|
||||
sampleMountinfoNoSrc = `15 20 0:3 / /proc rw,relatime - proc /proc rw
|
||||
16 20 0:15 / /sys rw,relatime - sysfs /sys rw
|
||||
17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1983516k,nr_inodes=495879,mode=755
|
||||
18 17 0:10 / /dev/pts rw,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000
|
||||
19 17 0:16 / /dev/shm rw,relatime - tmpfs tmpfs rw
|
||||
20 1 8:4 / / rw,noatime - ext3 /dev/sda4 rw,errors=continue,user_xattr,acl,barrier=0,data=ordered
|
||||
21 20 0:53 / /mnt/test rw,relatime shared:212 - tmpfs rw`
|
||||
)
|
||||
107
container/vfs/unfold.go
Normal file
107
container/vfs/unfold.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"iter"
|
||||
"path"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// MountInfoNode positions a [MountInfoEntry] in its mount hierarchy.
|
||||
type MountInfoNode struct {
|
||||
*MountInfoEntry
|
||||
FirstChild *MountInfoNode `json:"first_child"`
|
||||
NextSibling *MountInfoNode `json:"next_sibling"`
|
||||
|
||||
Clean string `json:"clean"`
|
||||
Covered bool `json:"covered"`
|
||||
}
|
||||
|
||||
// Collective returns an iterator over visible mountinfo nodes.
|
||||
func (n *MountInfoNode) Collective() iter.Seq[*MountInfoNode] {
|
||||
return func(yield func(*MountInfoNode) bool) { n.visit(yield) }
|
||||
}
|
||||
|
||||
func (n *MountInfoNode) visit(yield func(*MountInfoNode) bool) bool {
|
||||
if !n.Covered && !yield(n) {
|
||||
return false
|
||||
}
|
||||
for cur := n.FirstChild; cur != nil; cur = cur.NextSibling {
|
||||
if !cur.visit(yield) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Unfold unfolds the mount hierarchy and resolves covered paths.
|
||||
func (d *MountInfoDecoder) Unfold(target string) (*MountInfoNode, error) {
|
||||
targetClean := path.Clean(target)
|
||||
|
||||
var mountinfoSize int
|
||||
for range d.Entries() {
|
||||
mountinfoSize++
|
||||
}
|
||||
if err := d.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mountinfo := make([]*MountInfoNode, mountinfoSize)
|
||||
// mount ID to index lookup
|
||||
idIndex := make(map[int]int, mountinfoSize)
|
||||
// final entry to match target
|
||||
targetIndex := -1
|
||||
{
|
||||
i := 0
|
||||
for ent := range d.Entries() {
|
||||
mountinfo[i] = &MountInfoNode{Clean: path.Clean(ent.Target), MountInfoEntry: ent}
|
||||
idIndex[ent.ID] = i
|
||||
if mountinfo[i].Clean == targetClean {
|
||||
targetIndex = i
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if targetIndex == -1 {
|
||||
return nil, syscall.ESTALE
|
||||
}
|
||||
|
||||
for _, cur := range mountinfo {
|
||||
var parent *MountInfoNode
|
||||
if p, ok := idIndex[cur.Parent]; !ok {
|
||||
continue
|
||||
} else {
|
||||
parent = mountinfo[p]
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(cur.Clean, targetClean) {
|
||||
continue
|
||||
}
|
||||
if parent.Clean == cur.Clean {
|
||||
parent.Covered = true
|
||||
}
|
||||
|
||||
covered := false
|
||||
nsp := &parent.FirstChild
|
||||
for s := parent.FirstChild; s != nil; s = s.NextSibling {
|
||||
if strings.HasPrefix(cur.Clean, s.Clean) {
|
||||
covered = true
|
||||
break
|
||||
}
|
||||
|
||||
if strings.HasPrefix(s.Clean, cur.Clean) {
|
||||
*nsp = s.NextSibling
|
||||
} else {
|
||||
nsp = &s.NextSibling
|
||||
}
|
||||
}
|
||||
if covered {
|
||||
continue
|
||||
}
|
||||
*nsp = cur
|
||||
}
|
||||
|
||||
return mountinfo[targetIndex], nil
|
||||
}
|
||||
93
container/vfs/unfold_test.go
Normal file
93
container/vfs/unfold_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package vfs_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container/vfs"
|
||||
)
|
||||
|
||||
func TestUnfold(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
sample string
|
||||
target string
|
||||
wantErr error
|
||||
|
||||
want *vfs.MountInfoNode
|
||||
wantCollectF func(n *vfs.MountInfoNode) []*vfs.MountInfoNode
|
||||
wantCollectN []string
|
||||
}{
|
||||
{
|
||||
"no match",
|
||||
sampleMountinfoBase,
|
||||
"/mnt",
|
||||
syscall.ESTALE, nil, nil, nil,
|
||||
},
|
||||
{
|
||||
"cover",
|
||||
`33 1 0:33 / / rw,relatime shared:1 - tmpfs impure rw,size=16777216k,mode=755
|
||||
37 33 0:32 / /proc rw,nosuid,nodev,noexec,relatime shared:41 - proc proc rw
|
||||
551 33 0:121 / /mnt rw,relatime shared:666 - tmpfs tmpfs rw
|
||||
595 551 0:123 / /mnt rw,relatime shared:990 - tmpfs tmpfs rw
|
||||
611 595 0:142 / /mnt/etc rw,relatime shared:1112 - tmpfs tmpfs rw
|
||||
625 644 0:142 /passwd /mnt/etc/passwd rw,relatime shared:1112 - tmpfs tmpfs rw
|
||||
641 625 0:33 /etc/passwd /mnt/etc/passwd rw,relatime shared:1 - tmpfs impure rw,size=16777216k,mode=755
|
||||
644 611 0:33 /etc/passwd /mnt/etc/passwd rw,relatime shared:1 - tmpfs impure rw,size=16777216k,mode=755
|
||||
`, "/mnt", nil,
|
||||
mn(595, 551, 0, 123, "/", "/mnt", "rw,relatime", o("shared:990"), "tmpfs", "tmpfs", "rw", false,
|
||||
mn(611, 595, 0, 142, "/", "/mnt/etc", "rw,relatime", o("shared:1112"), "tmpfs", "tmpfs", "rw", false,
|
||||
mn(644, 611, 0, 33, "/etc/passwd", "/mnt/etc/passwd", "rw,relatime", o("shared:1"), "tmpfs", "impure", "rw,size=16777216k,mode=755", true,
|
||||
mn(625, 644, 0, 142, "/passwd", "/mnt/etc/passwd", "rw,relatime", o("shared:1112"), "tmpfs", "tmpfs", "rw", true,
|
||||
mn(641, 625, 0, 33, "/etc/passwd", "/mnt/etc/passwd", "rw,relatime", o("shared:1"), "tmpfs", "impure", "rw,size=16777216k,mode=755", false,
|
||||
nil, nil), nil), nil), nil), nil), func(n *vfs.MountInfoNode) []*vfs.MountInfoNode {
|
||||
return []*vfs.MountInfoNode{n, n.FirstChild, n.FirstChild.FirstChild.FirstChild.FirstChild}
|
||||
}, []string{"/mnt", "/mnt/etc", "/mnt/etc/passwd"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := vfs.NewMountInfoDecoder(strings.NewReader(tc.sample))
|
||||
got, err := d.Unfold(tc.target)
|
||||
|
||||
if !errors.Is(err, tc.wantErr) {
|
||||
t.Errorf("Unfold: error = %v, wantErr %v",
|
||||
err, tc.wantErr)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("Unfold:\ngot %s\nwant %s",
|
||||
mustMarshal(got), mustMarshal(tc.want))
|
||||
}
|
||||
|
||||
if err == nil && tc.wantCollectF != nil {
|
||||
t.Run("collective", func(t *testing.T) {
|
||||
wantCollect := tc.wantCollectF(got)
|
||||
gotCollect := slices.Collect(got.Collective())
|
||||
if !reflect.DeepEqual(gotCollect, wantCollect) {
|
||||
t.Errorf("Collective: \ngot %#v\nwant %#v",
|
||||
gotCollect, wantCollect)
|
||||
}
|
||||
t.Run("target", func(t *testing.T) {
|
||||
gotCollectN := slices.Collect[string](func(yield func(v string) bool) {
|
||||
for _, cur := range gotCollect {
|
||||
if !yield(cur.Clean) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if !reflect.DeepEqual(gotCollectN, tc.wantCollectN) {
|
||||
t.Errorf("Collective: got %q, want %q",
|
||||
gotCollectN, tc.wantCollectN)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
package dbus_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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)
|
||||
overridePath(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(context.Background(), 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 := "dbus: 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) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := p.Start(ctx, output, sandbox); err != nil {
|
||||
t.Fatalf("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("started wait of "+id, func(t *testing.T) {
|
||||
p.Close()
|
||||
if err := p.Wait(); err != nil {
|
||||
t.Errorf("Wait() error = %v\noutput: %s",
|
||||
err, output.String())
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func overridePath(t *testing.T) {
|
||||
proxyName := dbus.ProxyName
|
||||
dbus.ProxyName = "/nonexistent-xdg-dbus-proxy"
|
||||
t.Cleanup(func() {
|
||||
dbus.ProxyName = proxyName
|
||||
})
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package dbus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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
|
||||
ctx context.Context
|
||||
cancel context.CancelCauseFunc
|
||||
|
||||
name string
|
||||
session [2]string
|
||||
system [2]string
|
||||
sysP bool
|
||||
|
||||
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.String()
|
||||
}
|
||||
|
||||
if p.seal != nil {
|
||||
return p.seal.(fmt.Stringer).String()
|
||||
}
|
||||
|
||||
return "(unsealed dbus proxy)"
|
||||
}
|
||||
|
||||
// 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)...)
|
||||
p.sysP = true
|
||||
}
|
||||
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}
|
||||
}
|
||||
175
dbus/run.go
175
dbus/run.go
@@ -1,175 +0,0 @@
|
||||
package dbus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"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.
|
||||
func (p *Proxy) Start(ctx context.Context, 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
|
||||
|
||||
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)
|
||||
// xdg-dbus-proxy does not need to inherit the environment
|
||||
h.SetEnv(make([]string, 0))
|
||||
} 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 {
|
||||
return err
|
||||
} else {
|
||||
toolPath = s
|
||||
}
|
||||
}
|
||||
|
||||
// resolve libraries by parsing ldd output
|
||||
var proxyDeps []*ldd.Entry
|
||||
if toolPath != "/nonexistent-xdg-dbus-proxy" {
|
||||
if l, err := ldd.Exec(ctx, toolPath); err != nil {
|
||||
return err
|
||||
} else {
|
||||
proxyDeps = l
|
||||
}
|
||||
}
|
||||
|
||||
bc := &bwrap.Config{
|
||||
Unshare: nil,
|
||||
Hostname: "fortify-dbus",
|
||||
Chdir: "/",
|
||||
Syscall: &bwrap.SyscallPolicy{DenyDevel: true, Multiarch: true},
|
||||
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{}{}
|
||||
}
|
||||
if path.IsAbs(ent.Name) {
|
||||
roBindTarget[path.Dir(ent.Name)] = 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, toolPath, p.seal, argF, nil, nil)
|
||||
p.bwrap = bc
|
||||
}
|
||||
|
||||
if output != nil {
|
||||
h.Stdout(output).Stderr(output)
|
||||
}
|
||||
c, cancel := context.WithCancelCause(ctx)
|
||||
if err := h.Start(c, true); err != nil {
|
||||
cancel(err)
|
||||
return err
|
||||
}
|
||||
|
||||
p.helper = h
|
||||
p.ctx = c
|
||||
p.cancel = cancel
|
||||
return nil
|
||||
}
|
||||
|
||||
var proxyClosed = errors.New("proxy closed")
|
||||
|
||||
// Wait blocks until xdg-dbus-proxy exits and releases resources.
|
||||
func (p *Proxy) Wait() error {
|
||||
p.lock.RLock()
|
||||
defer p.lock.RUnlock()
|
||||
|
||||
if p.helper == nil {
|
||||
return errors.New("dbus: not started")
|
||||
}
|
||||
|
||||
errs := make([]error, 3)
|
||||
|
||||
errs[0] = p.helper.Wait()
|
||||
if p.cancel == nil &&
|
||||
errors.Is(errs[0], context.Canceled) &&
|
||||
errors.Is(context.Cause(p.ctx), proxyClosed) {
|
||||
errs[0] = nil
|
||||
}
|
||||
|
||||
// ensure socket removal so ephemeral directory is empty at revert
|
||||
if err := os.Remove(p.session[1]); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
errs[1] = err
|
||||
}
|
||||
if p.sysP {
|
||||
if err := os.Remove(p.system[1]); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
errs[2] = err
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// Close cancels the context passed to the helper instance attached to xdg-dbus-proxy.
|
||||
func (p *Proxy) Close() {
|
||||
p.lock.Lock()
|
||||
defer p.lock.Unlock()
|
||||
|
||||
if p.cancel == nil {
|
||||
panic("dbus: not started")
|
||||
}
|
||||
p.cancel(proxyClosed)
|
||||
p.cancel = nil
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package dbus_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestHelperChildStub(t *testing.T) {
|
||||
helper.InternalChildStub()
|
||||
}
|
||||
82
dist/comp/_hakurei
vendored
Normal file
82
dist/comp/_hakurei
vendored
Normal file
@@ -0,0 +1,82 @@
|
||||
#compdef hakurei
|
||||
|
||||
_hakurei_app() {
|
||||
__hakurei_files
|
||||
return $?
|
||||
}
|
||||
|
||||
_hakurei_run() {
|
||||
_arguments \
|
||||
'--id[Reverse-DNS style Application identifier, leave empty to inherit instance identifier]:id' \
|
||||
'-a[Application identity]: :_numbers' \
|
||||
'-g[Groups inherited by all container processes]: :_groups' \
|
||||
'-d[Container home directory]: :_files -/' \
|
||||
'-u[Passwd user name within sandbox]: :_users' \
|
||||
'--wayland[Enable connection to Wayland via security-context-v1]' \
|
||||
'-X[Enable direct connection to X11]' \
|
||||
'--dbus[Enable proxied connection to D-Bus]' \
|
||||
'--pulse[Enable direct connection to PulseAudio]' \
|
||||
'--dbus-config[Path to session bus proxy config file]: :_files -g "*.json"' \
|
||||
'--dbus-system[Path to system bus proxy config file]: :_files -g "*.json"' \
|
||||
'--mpris[Allow owning MPRIS D-Bus path]' \
|
||||
'--dbus-log[Force buffered logging in the D-Bus proxy]'
|
||||
}
|
||||
|
||||
_hakurei_ps() {
|
||||
_arguments \
|
||||
'--short[List instances only]'
|
||||
}
|
||||
|
||||
_hakurei_show() {
|
||||
_alternative \
|
||||
'instances:domains:__hakurei_instances' \
|
||||
'files:files:__hakurei_files'
|
||||
}
|
||||
|
||||
__hakurei_files() {
|
||||
_files -g "*.(json|hakurei)"
|
||||
return $?
|
||||
}
|
||||
|
||||
__hakurei_instances() {
|
||||
local -a out
|
||||
shift -p
|
||||
out=( ${(f)"$(_call_program commands hakurei ps --short 2>&1)"} )
|
||||
if (( $#out == 0 )); then
|
||||
_message "No active instances"
|
||||
else
|
||||
_describe "active instances" out
|
||||
fi
|
||||
return $?
|
||||
}
|
||||
|
||||
(( $+functions[_hakurei_commands] )) || _hakurei_commands()
|
||||
{
|
||||
local -a _hakurei_cmds
|
||||
_hakurei_cmds=(
|
||||
"app:Load app from configuration file"
|
||||
"run:Configure and start a permissive default sandbox"
|
||||
"show:Show live or local app configuration"
|
||||
"ps:List active instances"
|
||||
"version:Display version information"
|
||||
"license:Show full license text"
|
||||
"template:Produce a config template"
|
||||
"help:Show help message"
|
||||
)
|
||||
if (( CURRENT == 1 )); then
|
||||
_describe -t commands 'action' _hakurei_cmds || compadd "$@"
|
||||
else
|
||||
local curcontext="$curcontext"
|
||||
cmd="${${_hakurei_cmds[(r)$words[1]:*]%%:*}}"
|
||||
if (( $+functions[_hakurei_$cmd] )); then
|
||||
_hakurei_$cmd
|
||||
else
|
||||
_message "no more options"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
_arguments -C \
|
||||
'-v[Increase log verbosity]' \
|
||||
'--json[Serialise output in JSON when applicable]' \
|
||||
'*::hakurei command:_hakurei_commands'
|
||||
0
dist/fsurc.default → dist/hsurc.default
vendored
0
dist/fsurc.default → dist/hsurc.default
vendored
12
dist/install.sh
vendored
12
dist/install.sh
vendored
@@ -1,12 +1,12 @@
|
||||
#!/bin/sh
|
||||
cd "$(dirname -- "$0")" || exit 1
|
||||
|
||||
install -vDm0755 "bin/fortify" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fortify"
|
||||
install -vDm0755 "bin/fpkg" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fpkg"
|
||||
install -vDm0755 "bin/hakurei" "${HAKUREI_INSTALL_PREFIX}/usr/bin/hakurei"
|
||||
install -vDm0755 "bin/planterette" "${HAKUREI_INSTALL_PREFIX}/usr/bin/planterette"
|
||||
|
||||
install -vDm6511 "bin/fsu" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fsu"
|
||||
if [ ! -f "${FORTIFY_INSTALL_PREFIX}/etc/fsurc" ]; then
|
||||
install -vDm0400 "fsurc.default" "${FORTIFY_INSTALL_PREFIX}/etc/fsurc"
|
||||
install -vDm6511 "bin/hsu" "${HAKUREI_INSTALL_PREFIX}/usr/bin/hsu"
|
||||
if [ ! -f "${HAKUREI_INSTALL_PREFIX}/etc/hsurc" ]; then
|
||||
install -vDm0400 "hsurc.default" "${HAKUREI_INSTALL_PREFIX}/etc/hsurc"
|
||||
fi
|
||||
|
||||
install -vDm0644 "comp/_fortify" "${FORTIFY_INSTALL_PREFIX}/usr/share/zsh/site-functions/_fortify"
|
||||
install -vDm0644 "comp/_hakurei" "${HAKUREI_INSTALL_PREFIX}/usr/share/zsh/site-functions/_hakurei"
|
||||
15
dist/release.sh
vendored
15
dist/release.sh
vendored
@@ -1,18 +1,19 @@
|
||||
#!/bin/sh -e
|
||||
cd "$(dirname -- "$0")/.."
|
||||
VERSION="${FORTIFY_VERSION:-untagged}"
|
||||
pname="fortify-${VERSION}"
|
||||
VERSION="${HAKUREI_VERSION:-untagged}"
|
||||
pname="hakurei-${VERSION}"
|
||||
out="dist/${pname}"
|
||||
|
||||
mkdir -p "${out}"
|
||||
cp -v "README.md" "dist/fsurc.default" "dist/install.sh" "${out}"
|
||||
cp -rv "comp" "${out}"
|
||||
cp -v "README.md" "dist/hsurc.default" "dist/install.sh" "${out}"
|
||||
cp -rv "dist/comp" "${out}"
|
||||
|
||||
go generate ./...
|
||||
go build -trimpath -v -o "${out}/bin/" -ldflags "-s -w -buildid= -extldflags '-static'
|
||||
-X git.gensokyo.uk/security/fortify/internal.Version=${VERSION}
|
||||
-X git.gensokyo.uk/security/fortify/internal.Fsu=/usr/bin/fsu
|
||||
-X main.Fmain=/usr/bin/fortify" ./...
|
||||
-X hakurei.app/internal.version=${VERSION}
|
||||
-X hakurei.app/internal.hmain=/usr/bin/hakurei
|
||||
-X hakurei.app/internal.hsu=/usr/bin/hsu
|
||||
-X main.hmain=/usr/bin/hakurei" ./...
|
||||
|
||||
rm -f "./${out}.tar.gz" && tar -C dist -czf "${out}.tar.gz" "${pname}"
|
||||
rm -rf "./${out}"
|
||||
|
||||
46
error.go
46
error.go
@@ -1,46 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"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) {
|
||||
log.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
|
||||
log.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
|
||||
log.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
|
||||
log.Println("invalid error type returned by revert:", ei)
|
||||
} else {
|
||||
// print inner *app.BaseError message
|
||||
log.Print(eb.Message())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user