Compare commits

...
Sign in to create a new pull request.

126 commits

Author SHA1 Message Date
930ee1afce
chore: nix flake update 2025-07-24 01:05:36 +02:00
63dd80d469
chore(sysext): add containerd 2025-07-23 21:18:56 +02:00
71531c8bb8
fix(make-sysext): use find to find only files 2025-07-22 22:22:33 +02:00
584e937600
chore(debug-tools): add file command 2025-07-22 15:55:52 +02:00
ea0dc138fb
fix: compress kernel modules 2025-07-19 17:26:20 +02:00
0883e468c6
chore(kernel): update 2025-07-19 09:17:06 +02:00
44b3449622 Merge pull request 'sys extensions and versioning thinkering' () from lsjostro/push-uvlynlupusqw into main
Reviewed-on: 
2025-07-18 21:28:33 +02:00
6e691c41d2
wip: sys extensions and versioning thinkering 2025-07-18 21:26:55 +02:00
a7bfb1509b
chore(make-sysext): support different systemd targets 2025-06-26 16:37:07 +02:00
d5fb0de315
chore(make-sysext): create content and package lists 2025-06-26 11:20:04 +02:00
3de146ea71
chore(flake): update 2025-06-25 21:02:18 +02:00
8a9b26a34b
chore(flake): some refactoring to include revision if available 2025-06-25 19:28:02 +02:00
b9f24be9a0
fix: dbus broker 2025-06-24 21:27:18 +02:00
80bc499287
fix(make-sysext): make services optional 2025-06-24 10:49:07 +02:00
727b4c3481
chore(profile): add PS1 prompt 2025-06-24 10:30:53 +02:00
224dd93780
chore: add a default /etc/profile 2025-06-24 10:07:22 +02:00
0f91ef4603
feat(debug-tools): add terminfo 2025-06-24 08:56:35 +02:00
f2fe23cd07
feat(debug-tools): add sftp server to dropbear 2025-06-23 21:05:51 +02:00
d6e90446ed
feat: add service units to sysext 2025-06-23 10:56:39 +02:00
d6b871878d
chore: update kernel 2025-06-23 10:56:29 +02:00
a1b6c71c11
fix(rootfs): install fsck from util-linux 2025-06-20 11:39:10 +02:00
0cfb887c07
fix: install fsck.fat to be able to repair ESP 2025-06-20 10:57:59 +02:00
31809c91f8
fix(linux-firmware): dont package amd-ucode 2025-06-18 18:55:26 +02:00
353faef3ae
fix(linux-firmware): package remaining fw into "other" 2025-06-18 14:00:22 +02:00
5ed34d22ce
feat(linux-firmware): sysext packaging of linux firmware 2025-06-18 13:18:36 +02:00
dff614f46d
chore: refactor systemd sysext packages 2025-06-17 22:28:23 +02:00
22106e96a8
chore: update readme 2025-06-17 11:33:45 +02:00
1cf254e94d
fix: remove old patosPkgs ref 2025-06-17 10:50:47 +02:00
b53d72c676 Merge pull request 'feat: add ARM kernel config' () from lsjostro/push-unmzwunrxrso into main
Reviewed-on: 
2025-06-17 08:25:18 +02:00
3aacf80380
feat: add ARM kernel config 2025-06-17 08:24:29 +02:00
217ff2d4a8
chore: add qemu script to launch aarch64 image 2025-06-13 10:30:38 +02:00
52a38d60c0
chore(flake): use inherit 2025-06-13 08:33:34 +02:00
f856983210
chore: move overlay to own file 2025-06-13 08:17:14 +02:00
49c09d772d
chore: update kernel 2025-06-12 21:57:23 +02:00
19c91e16ab
chore: s/cpuArch/microcode 2025-06-12 19:39:39 +02:00
d745cbe1c2
fix: aarch64 builds needs nativeBuildInputs 2025-06-12 16:55:57 +02:00
760c8fe637
feat: support cross compile to aarch64 2025-06-12 15:57:54 +02:00
bd002f2d25
fix: explict use nativeBuildInputs 2025-06-12 10:55:22 +02:00
34c83b7c3b
fix(kexec-tools): build using autoconf 2025-06-12 10:52:43 +02:00
6f84c2c41d
feat: add firewall tools as sysext 2025-06-11 17:57:23 +02:00
e85353bc35
chore: better compression for sysext images 2025-06-11 13:42:38 +02:00
6361308cd0
chore: nix flake update and kernel upgrade 2025-06-09 12:36:04 +02:00
396a97cce4 Merge pull request 'feat: start using systemd from main line' () from lsjostro/push-mvyvrwvlzwrr into main
Reviewed-on: 
2025-06-04 18:51:02 +02:00
827b2c3d0f
feat: start using systemd from main line 2025-06-04 14:04:52 +02:00
2729e07996
chore: kernel update 2025-06-03 08:16:50 +02:00
df4c60d87c
chore: kernel and systemd update 2025-05-30 16:00:02 +02:00
c883ff1cb2
Revert sysupdate fix due to a bug in systemd.
sysext need to be unmerged before sysupdate can be used.
https://github.com/systemd/systemd/pull/36617/
fix in main but not backported to stable yet.
2025-05-23 13:15:16 +02:00
d42406c6dc
fix: sysupdate wont work with out systemd.volatile set to overlay 2025-05-23 12:10:11 +02:00
7c0d0a099d
chore: nix flake update 2025-05-20 21:05:54 +02:00
8ee40679fc
chore: os update 2025-05-12 19:40:51 +02:00
af2a063ff2
chore: kernel upgrade 2025-05-07 06:26:16 +02:00
b7e526454b
chore: nix update 2025-05-06 18:20:37 +02:00
15227256ec
chore: kernel upgrade 2025-04-19 23:06:44 +02:00
92c204231b
chore: nix flake update 2025-04-19 22:56:12 +02:00
58861e6de6
chore: upgrade systemd 2025-04-17 19:10:38 +02:00
d10bd7bb04
fix(rootfs): symlink /var/tmp to /tmp if no state partition available
this enable systemd networkd and resolved to work
2025-03-26 14:22:17 +01:00
c470bf6d59
chore: track upstream nixpkgs for our forks 2025-03-26 11:55:25 +01:00
242294eb8d
chore: nix flake update 2025-03-26 11:13:46 +01:00
bb708e3e61
feat(image): parameter to include microcode and secureboot 2025-03-26 10:59:38 +01:00
2841610f41
chore: bump kernel version 2025-03-26 10:32:09 +01:00
a7de3101a8
chore: include kernel modules in rootfs as sysext 2025-03-21 10:50:42 +01:00
91191a2947
revert version 2025-03-20 14:01:50 +01:00
4166b4c1fb
feat: kernel modules as system extensions 2025-03-20 14:00:55 +01:00
c748e17279
chore(sb): use systemd kernel cmdline condition 2025-03-19 23:57:21 +01:00
6819565d79
qemu: remove unused ssh port forward 2025-03-19 20:29:11 +01:00
91a5646555
fix: include uuid in sysupdate images 2025-03-19 14:03:50 +01:00
a7b86fd03e
feat: add sysupdate definitions 2025-03-19 11:32:17 +01:00
8fb3174c78
feat: enroll secure boot at first boot 2025-03-18 21:45:07 +01:00
dc8ed2a774
feat: enable factory reset 2025-03-17 22:23:11 +01:00
df3a42da4b
chore: more clean up 2025-03-17 17:08:33 +01:00
a3e2a970f8
chore: clean up 2025-03-17 16:53:45 +01:00
1725120a49
chore: upgrade kernel 2025-03-15 18:51:59 +01:00
b619c6f01d
chore: remove result symlink 2025-03-15 18:45:39 +01:00
7376743266
chore: clean up 2025-03-14 23:23:14 +01:00
1f1c93b775
feat: enable secure boot 2025-03-14 11:39:23 +01:00
1fcc45dd32
feat: add factory reset UKI 2025-03-14 08:42:02 +01:00
2c2d212e25
fix: our own derivation for the kernel in order to be able to sign modules 2025-03-13 17:27:36 +01:00
3dec49b2e4
chore(qemu): enable secure boot 2025-03-13 14:46:27 +01:00
1fcccfcd7c
chore(debug-tools): add strace and binutils 2025-03-12 15:39:01 +01:00
723c7efa32
chore(debug-tools): more tools for the people 🚀 2025-03-12 14:38:28 +01:00
865d73abab
chore(debug-tools): add a couple of useful tools 2025-03-12 14:13:11 +01:00
4c0ae9086b
chore(openssl): remove dist files from ssldir 2025-03-12 13:38:50 +01:00
5ecfd546f6
fix: we have to build our own openssl to use standard paths 2025-03-12 12:52:15 +01:00
4ecf8ead2a
chore: add lib for making systemd sysexts 2025-03-12 10:41:09 +01:00
e49c2b22b5
chore: install ca cert bundle 2025-03-10 12:12:58 +01:00
55ac59e2b3
chore: add subvolumes state partition 2025-03-09 14:43:57 +01:00
e907d0d3d3
fix: rootfs now with verity and A/B prep 2025-03-07 15:19:41 +01:00
3f443a9e9b
chore: autologin as root for now 2025-03-06 17:18:17 +01:00
d1e25bdddf
chore: upgrade systemd to latest stable 2025-03-06 16:26:13 +01:00
658b5af153
chore: even better erofs compression 2025-03-06 16:16:25 +01:00
62dd1ca5bf
feat: enable conf/sys ext services and make /etc read-only without overlay 2025-03-05 22:04:38 +01:00
18c8e76850
revert to static machine id for now 2025-03-05 10:08:47 +01:00
be4efca9a5
chore: temporary generate machine-id on boot until we have a confext 2025-03-05 10:00:10 +01:00
0a129b5489
chore: clean up 2025-03-05 09:13:18 +01:00
879f74befa
chore: remove unused logind and sysuser for dbus svc 2025-03-05 08:38:08 +01:00
12bacf271d
feat: generate passwd/group with systemd-sysusers 2025-03-04 23:51:08 +01:00
8e61f85f72
chore: clean up var-repart config 2025-03-04 15:42:12 +01:00
e5367bac84
chore: more clean up 2025-03-04 14:20:31 +01:00
529061df5e
chore: clean up comments 2025-03-04 14:08:53 +01:00
83bb3599a4
fix(repart): depend on sysroot-run mount 2025-03-04 13:56:18 +01:00
10090a75b0
fix(image): finally have working mount of encrypted volumes! 2025-03-04 12:10:18 +01:00
adb2e90c13
fix(image): image need to include devicemapper setup tools and udev rules 2025-03-03 16:13:30 +01:00
0a6fc3af49
chore: enable default networking and make root own erofs files 2025-02-27 16:42:11 +01:00
aa4f69d891
fix: we need to roll our own versions of tpm2-tools and tpm2-tss 2025-02-27 16:35:50 +01:00
57f83bd4ac
chore: make erofs with --all-root flag 2025-02-27 08:18:24 +01:00
7365ef8918
feat(image): install upstream kexec which now have support for UKIs 2025-02-26 14:40:06 +01:00
0a0e9127e0
fix(systemd): set path to kexec 2025-02-26 10:45:05 +01:00
ca54cefe36
fix: mount race condition of patos-state 2025-02-26 10:22:56 +01:00
a3aab1ea5c
chore: flake nix cleanup 2025-02-25 23:09:11 +01:00
0ed83a6d27
feat(image): add overlay to /etc and use busybox getty for login prompt 2025-02-25 21:55:53 +01:00
3374541b3a
feat(image): switch to btrfs for patos-state 2025-02-25 21:07:57 +01:00
b3ad9f9962
feat(image): fix osrel in uki 2025-02-25 18:02:49 +01:00
e4ebf7ea7f
feat(image): make /var stateful 2025-02-25 14:50:43 +01:00
e196cf729c
feat(image): switching root 2025-02-25 13:13:48 +01:00
6899203860
feat(systemd-repart): fix ESP. now its booting 2025-02-24 23:53:44 +01:00
af78f1c930
feat(systemd-repart): build image 2025-02-24 16:29:53 +01:00
e7470498e5
fix: create derivation for initrd creation 2025-02-24 15:12:43 +01:00
9ff916d0a3
chore: xz compressed initrd and remove systemd patch 2025-02-24 09:27:17 +01:00
7ecbd46b53 Merge pull request 'chore: rootfs pkg' () from lsjostro/push-ptznrypypruv into main
Reviewed-on: 
2025-02-21 18:48:36 +01:00
a689fa9925
chore: rootfs pkg 2025-02-21 18:44:46 +01:00
6dc82ee21f Merge pull request 'chore: add dbus-broker' () from lsjostro/push-tsrlsoumoytp into main
Reviewed-on: 
2025-02-21 10:44:36 +01:00
0dfda7560f
chore: add dbus-broker 2025-02-21 10:40:09 +01:00
0f7958b596 Merge pull request 'Build image from scratch / without NixOS.' () from dln/push-wxvqmqvrsxzv into main
Reviewed-on: 
2025-02-19 15:24:42 +01:00
2ad53505eb Merge pull request 'silly uki image with the systemd-ukify tooling' () from lsjostro/push-mzqkykluxntr into dln/push-wxvqmqvrsxzv
Reviewed-on: 
2025-02-19 15:23:36 +01:00
dbd4e729de
silly uki image with the systemd-ukify tooling 2025-02-19 15:20:28 +01:00
52986e7e70 Merge pull request 'chore(systemd): remove nix store ref and disable some features' () from lsjostro/push-tpqplksttywz into dln/push-wxvqmqvrsxzv
Reviewed-on: 
2025-02-17 11:34:40 +01:00
38 changed files with 12234 additions and 81 deletions

1
.gitignore vendored
View file

@ -4,6 +4,7 @@
.task
/result
/target
/out
.*.swp
.*.swo
.nixos-test-history

View file

@ -55,6 +55,6 @@ PatOS is a minimal, immutable Linux distribution specialized for the Patagia Pla
== License
Copyright (C) 2024 Patagia AB
Copyright (C) 2025 Patagia AB
Unless otherwise noted, all components are licenced under the Mozilla Public License Version 2.0.

6
flake.lock generated
View file

@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1739020877,
"narHash": "sha256-mIvECo/NNdJJ/bXjNqIh8yeoSjVLAuDuTUzAo7dzs8Y=",
"lastModified": 1752950548,
"narHash": "sha256-NS6BLD0lxOrnCiEOcvQCDVPXafX1/ek1dfJHX1nUIzc=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a79cfe0ebd24952b580b1cf08cd906354996d547",
"rev": "c87b95e25065c028d31a94f06a62927d18763fdf",
"type": "github"
},
"original": {

View file

@ -15,17 +15,52 @@
flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs { inherit system; };
buildParams = {
arch = {
"x86_64-linux" = "x86-64";
"aarch64-linux" = "arm64";
};
revision = self.shortRev or self.dirtyShortRev or "dirty";
updateUrl = "http://10.0.2.2:8000/";
secureBoot = "false";
version = "0.0.1";
};
overlay = import ./overlays (buildParams // { });
pkgs = import nixpkgs {
inherit system;
overlays = [ overlay ];
};
pkgsCross = import nixpkgs {
inherit system;
overlays = [ overlay ];
crossSystem = {
config = "aarch64-unknown-linux-gnu";
};
};
in
{
packages = {
default = self.packages.${system}.image;
image = pkgs.writeShellScriptBin "image" ''
echo "make image here..."
'';
kernel = pkgs.callPackage ./kernel { };
systemd = pkgs.callPackage ./systemd { };
image = pkgs.callPackage ./pkgs/image (buildParams // { microcode = "intel"; });
image-aarch64 = pkgsCross.callPackage ./pkgs/image (buildParams // { });
qemu-uefi-tpm = pkgs.callPackage ./utils/qemu-uefi-tpm.nix { };
qemu-aarch64-uefi-tpm = pkgs.callPackage ./utils/qemu-aarch64-uefi-tpm.nix { };
# systemd sysext packages
debug-tools = pkgs.callPackage ./pkgs/sysext/debug-tools.nix (buildParams // { });
debug-tools-aarch64 = pkgsCross.callPackage ./pkgs/sysext/debug-tools.nix (buildParams // { });
firewall-tools = pkgs.callPackage ./pkgs/sysext/firewall-tools.nix (buildParams // { });
firewall-tools-aarch64 = pkgsCross.callPackage ./pkgs/sysext/firewall-tools.nix (buildParams // { });
containerd = pkgs.callPackage ./pkgs/sysext/containerd.nix (buildParams // { });
containerd-aarch64 = pkgsCross.callPackage ./pkgs/sysext/containerd.nix (buildParams // { });
linux-firmware = pkgs.callPackage ./pkgs/linux-firmware { };
};
checks = {
@ -39,11 +74,10 @@
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
erofs-utils
just
nixd
nixfmt-rfc-style
squashfs-tools-ng
self.packages.${system}.qemu-uefi-tpm
];
};

View file

@ -1,16 +0,0 @@
{ pkgs, ... }:
let
version = "6.13.2";
in
pkgs.linuxPackagesFor (
pkgs.linuxManualConfig {
version = "${version}-patos1";
modDirVersion = version;
src = pkgs.fetchurl {
url = "https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${version}.tar.xz";
hash = "sha256-zfYpgZBru+lwGutzxPn8yAegmEbCiHMWY9YnF+0a5wU=";
};
configfile = ./generic.config;
allowImportFromDerivation = true;
}
)

224
lib/make-sysext.nix Normal file
View file

@ -0,0 +1,224 @@
{
lib,
runCommand,
pkgs,
name,
packages,
services ? [],
osId ? "patos",
version ? null,
arch ? "x86-64",
updateUrl ? null,
}:
let
metadata = {
ID = osId;
VERSION_ID = osId;
IMAGE_ID = name;
IMAGE_VERSION = version;
ARCHITECTURE = arch;
} // lib.optionalAttrs (services != []) { EXTENSION_RELOAD_MANAGER = "1"; };
metadataFile = lib.concatStringsSep "\n" (
lib.mapAttrsToList (k: v: "${k}=${v}") (lib.filterAttrs (_: v: v != null) metadata)
);
versionString = "${version}-${arch}";
doCopy =
{
drv,
prefix ? "usr",
path,
destpath ? null,
}:
"do_copy ${prefix} ${drv} ${path} ${drv.name} " + builtins.concatStringsSep "," (map (l: l.shortName or "unknown") (lib.toList (drv.meta.license or []))) + lib.optionalString (destpath != null) " ${destpath}";
in
runCommand name
{
passthru.name = name;
inherit metadataFile;
passAsFile = [ "metadataFile" ];
env = {
SYSTEMD_REPART_MKFS_OPTIONS_EROFS = "--all-root -zlz4hc,12 -C1048576 -Efragments,dedupe,ztailpacking";
};
nativeBuildInputs = [
pkgs.erofs-utils
pkgs.cryptsetup
pkgs.gawk
pkgs.jq
];
}
''
set -ex -o pipefail
do_copy () {
local prefix="$1"
local drv="$2"
local path="$3"
local pkgname="$4"
local license="$5"
local destpath="''${6:-$path}"
local srcfile
local destdir
local destfile
srcfile="$drv/$path"
destfile="$out/tree/$prefix/$destpath"
destdir="$(dirname -- "$destfile")"
echo "pkgname=\"$pkgname\",licenses=\""$license"\"" >> $out/.tmp-pkgs.txt
mkdir -pv "$destdir"
# recursively copy if ending with /
if [[ "$destfile" =~ /$ ]]; then
basedir="$(dirname -- "$destfile")"
chmod -R 755 "$basedir"
# remove if exists
for f in $(find $srcfile -type f); do
basename="$(basename -- "$f")"
rm -f "$destfile/$basename"
done
cp -rPv "$srcfile" "$basedir"
chmod -R 755 "$basedir"
for f in $(find $destfile -type f); do
interpreter=$(patchelf --print-interpreter $f || echo "")
[ -n "$interpreter" ] && ldLinux=$(basename $interpreter)
patchelf --set-interpreter /lib/$ldLinux $f || true
patchelf --set-rpath /usr/lib $f || true
done
return
fi
if [ -f "$drv" ]; then
srcfile="$drv"
fi
cp -Pv "$srcfile" "$destfile"
chmod 755 "$destfile"
interpreter=$(patchelf --print-interpreter $destfile || echo "")
[ -n "$interpreter" ] && ldLinux=$(basename $interpreter)
patchelf --set-rpath /usr/lib $destfile || true
patchelf --set-interpreter /lib/$ldLinux $destfile || true
}
do_service () {
local unit="$1"
local content="$2"
local unit_file="$out/tree/usr/lib/systemd/system/$unit"
mkdir -p $out/tree/usr/lib/systemd/system
echo "$content" > $unit_file
# look for [Install] section and WantedBy in unit
if ! grep -q "^\[Install\]" "$unit_file"; then
echo "No [Install] section found in $unit_file"
return
fi
local wanted_by=$(sed -n '/^\[Install\]/,/^\[/{/^WantedBy=/s/^WantedBy=//p}' "$unit_file")
if [ -z "$wanted_by" ]; then
echo "No WantedBy found in [Install] section of $unit_file"
exit 1
fi
mkdir -p $out/tree/usr/lib/systemd/system/"$wanted_by".wants
ln -s ../$unit $out/tree/usr/lib/systemd/system/"$wanted_by".wants/$unit
}
mkdir -p $out/tree
${lib.concatStringsSep "\n" (map doCopy packages)}
${lib.concatStringsSep "\n" (map (service: "do_service '${service.unit}' '${service.content}'") services)}
# bake metadata into the structure
if ! [ -f $out/tree/usr/lib/extension-release.d/extension-release."${name}" ]; then
mkdir -p $out/tree/usr/lib/extension-release.d
cat "$metadataFilePath" > $out/tree/usr/lib/extension-release.d/extension-release."${name}"
fi
if [ -n "${updateUrl}" ]; then
mkdir -p $out/tree/usr/lib/sysupdate.d
ft=(raw)
for i in "''${!ft[@]}"; do
cat << EOF > $out/tree/usr/lib/sysupdate.d/9"$i"-"${name}".transfer
[Source]
Type=url-file
Path=${updateUrl}
MatchPattern=${name}-@v-%a.''${ft[i]}
[Target]
InstancesMax=3
Type=regular-file
MatchPattern=extensions.d/${name}-@v-%a.''${ft[i]}
Path=/var/lib/
CurrentSymlink=extensions/${name}.''${ft[i]}
[Transfer]
Verify=no
EOF
done
fi
pushd $out
mkdir $out/sysext.repart.d
cat << EOF > $out/sysext.repart.d/10-root.conf
[Partition]
Type=root
Format=erofs
CopyFiles=/usr/
CopyFiles=/opt/
AddValidateFS=false
Verity=data
VerityMatchKey=root
Minimize=best
EOF
cat << EOF > $out/sysext.repart.d/20-root-verity.conf
[Partition]
Type=root-verity
AddValidateFS=false
Verity=hash
VerityMatchKey=root
Minimize=best
EOF
${pkgs.patos.systemd}/usr/bin/systemd-repart \
--make-ddi=sysext \
--definitions=$out/sysext.repart.d \
--copy-source=./tree \
--pretty=no \
"$name"-${versionString}.raw
ln -s "$name"-${versionString}.raw "$name".raw
# TODO: pcks7 signature
# openssl smime -sign -nocerts -noattr -binary -in ${name}.roothash \
# -inkey key.pem -signer cert.pem -outform der -out ${name}.roothash.p7s
# create contents list
pushd tree
find . -ls > $out/"$name"-${versionString}_contents.txt
popd
# create nixpkgs packages list
sort -u $out/.tmp-pkgs.txt > $out/"$name"-${versionString}_packages.txt
rm -f $out/.tmp-pkgs.txt
jq -R -s 'split("\n") | map(select(length > 0)) | map(capture("pkgname=\"(?<name>[^\"]*)\",licenses=\"(?<licenses>[^\"]*)\"") | .licenses |= split(",")) | map(select(. != null))' $out/"$name"-${versionString}_packages.txt > $out/"$name"-${versionString}_packages.json
rm -rf tree
rm -rf $out/sysext.repart.d
sha256sum * > SHA256SUMS
ln -s SHA256SUMS SHA256SUMS.asc
# TODO: add gpg signature
popd
''

23
overlays/default.nix Normal file
View file

@ -0,0 +1,23 @@
{
version,
revision,
...
}:
final: prev: {
patos = prev.lib.makeScope prev.newScope (self: {
kernel = final.callPackage ../pkgs/kernel { };
glibc = final.callPackage ../pkgs/glibc { };
busybox = final.callPackage ../pkgs/busybox { };
openssl = final.callPackage ../pkgs/openssl { };
kexec = final.callPackage ../pkgs/kexec-tools { };
lvm2 = final.callPackage ../pkgs/lvm2 { };
tpm2-tools = final.callPackage ../pkgs/tpm2-tools { };
tpm2-tss = final.callPackage ../pkgs/tpm2-tss { };
systemd = final.callPackage ../pkgs/systemd { };
dbus-broker = final.callPackage ../pkgs/dbus-broker { };
rootfs = final.callPackage ../pkgs/rootfs/mkrootfs.nix { inherit version revision; };
initrd = final.callPackage ../pkgs/rootfs/mkinitrd.nix { };
});
}

View file

@ -0,0 +1,37 @@
diff --git a/Makefile b/Makefile
index 6fedcffba..3385836c4 100644
--- a/Makefile
+++ b/Makefile
@@ -271,8 +271,8 @@ export quiet Q KBUILD_VERBOSE
# Look for make include files relative to root of kernel src
MAKEFLAGS += --include-dir=$(srctree)
-HOSTCC = gcc
-HOSTCXX = g++
+HOSTCC = cc
+HOSTCXX = c++
HOSTCFLAGS :=
HOSTCXXFLAGS :=
# We need some generic definitions
@@ -289,7 +289,7 @@ MAKEFLAGS += -rR
# Make variables (CC, etc...)
AS = $(CROSS_COMPILE)as
-CC = $(CROSS_COMPILE)gcc
+CC = $(CROSS_COMPILE)cc
LD = $(CC) -nostdlib
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
diff --git a/scripts/Makefile.IMA b/scripts/Makefile.IMA
index f155108d7..185257064 100644
--- a/scripts/Makefile.IMA
+++ b/scripts/Makefile.IMA
@@ -39,7 +39,7 @@ ifndef HOSTCC
HOSTCC = cc
endif
AS = $(CROSS_COMPILE)as
-CC = $(CROSS_COMPILE)gcc
+CC = $(CROSS_COMPILE)cc
LD = $(CC) -nostdlib
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar

208
pkgs/busybox/default.nix Normal file
View file

@ -0,0 +1,208 @@
{
stdenv,
lib,
pkgs,
buildPackages,
fetchurl,
fetchpatch,
fetchFromGitLab,
enableStatic ? stdenv.hostPlatform.isStatic,
enableMinimal ? false,
enableAppletSymlinks ? true,
# Allow forcing musl without switching stdenv itself, e.g. for our bootstrapping:
# nix build -f pkgs/top-level/release.nix stdenvBootstrapTools.x86_64-linux.dist
useMusl ? stdenv.hostPlatform.libc == "musl",
musl,
extraConfig ? "",
}:
assert stdenv.hostPlatform.libc == "musl" -> useMusl;
let
configParser = ''
function parseconfig {
while read LINE; do
NAME=`echo "$LINE" | cut -d \ -f 1`
OPTION=`echo "$LINE" | cut -d \ -f 2`
if ! [[ "$NAME" =~ ^CONFIG_ ]]; then continue; fi
echo "parseconfig: removing $NAME"
sed -i /$NAME'\(=\| \)'/d .config
echo "parseconfig: setting $NAME=$OPTION"
echo "$NAME=$OPTION" >> .config
done
}
'';
libcConfig = lib.optionalString useMusl ''
CONFIG_FEATURE_UTMP n
CONFIG_FEATURE_WTMP n
'';
# The debian version lags behind the upstream version and also contains
# a debian-specific suffix. We only fetch the debian repository to get the
# default.script
debianVersion = "1.30.1-6";
debianSource = fetchFromGitLab {
domain = "salsa.debian.org";
owner = "installer-team";
repo = "busybox";
rev = "debian/1%${debianVersion}";
sha256 = "sha256-6r0RXtmqGXtJbvLSD1Ma1xpqR8oXL2bBKaUE/cSENL8=";
};
debianDispatcherScript = "${debianSource}/debian/tree/udhcpc/etc/udhcpc/default.script";
outDispatchPath = "$out/default.script";
in
stdenv.mkDerivation rec {
pname = "busybox";
version = pkgs.busybox.version;
# Note to whoever is updating busybox: please verify that:
# nix-build pkgs/stdenv/linux/make-bootstrap-tools.nix -A test
# still builds after the update.
src = pkgs.busybox.src;
hardeningDisable = [
"format"
"pie"
] ++ lib.optionals enableStatic [ "fortify" ];
patches = [
(fetchurl {
name = "CVE-2022-28391.patch";
url = "https://git.alpinelinux.org/aports/plain/main/busybox/0001-libbb-sockaddr2str-ensure-only-printable-characters-.patch?id=ed92963eb55bbc8d938097b9ccb3e221a94653f4";
sha256 = "sha256-yviw1GV+t9tbHbY7YNxEqPi7xEreiXVqbeRyf8c6Awo=";
})
(fetchurl {
name = "CVE-2022-28391.patch";
url = "https://git.alpinelinux.org/aports/plain/main/busybox/0002-nslookup-sanitize-all-printed-strings-with-printable.patch?id=ed92963eb55bbc8d938097b9ccb3e221a94653f4";
sha256 = "sha256-vl1wPbsHtXY9naajjnTicQ7Uj3N+EQ8pRNnrdsiow+w=";
})
(fetchpatch {
name = "CVE-2022-48174.patch"; # https://bugs.busybox.net/show_bug.cgi?id=15216
url = "https://git.busybox.net/busybox/patch/?id=d417193cf37ca1005830d7e16f5fa7e1d8a44209";
hash = "sha256-mpDEwYncpU6X6tmtj9xM2KCrB/v2ys5bYxmPPrhm6es=";
})
(fetchpatch {
name = "CVE-2023-42366.patch"; # https://bugs.busybox.net/show_bug.cgi?id=15874
# This patch is also used by Alpine, see https://git.alpinelinux.org/aports/tree/main/busybox/0037-awk.c-fix-CVE-2023-42366-bug-15874.patch
url = "https://bugs.busybox.net/attachment.cgi?id=9697";
hash = "sha256-2eYfLZLjStea9apKXogff6sCAdG9yHx0ZsgUBaGfQIA=";
})
(fetchpatch {
name = "CVE-2023-42363.patch"; # https://bugs.busybox.net/show_bug.cgi?id=15865
url = "https://git.launchpad.net/ubuntu/+source/busybox/plain/debian/patches/CVE-2023-42363.patch?id=c9d8a323b337d58e302717d41796aa0242963d5a";
hash = "sha256-1W9Q8+yFkYQKzNTrvndie8QuaEbyAFL1ZASG2fPF+Z4=";
})
(fetchpatch {
name = "CVE-2023-42364_CVE-2023-42365.patch"; # https://bugs.busybox.net/show_bug.cgi?id=15871 https://bugs.busybox.net/show_bug.cgi?id=15868
url = "https://git.alpinelinux.org/aports/plain/main/busybox/CVE-2023-42364-CVE-2023-42365.patch?id=8a4bf5971168bf48201c05afda7bee0fbb188e13";
hash = "sha256-nQPgT9eA1asCo38Z9X7LR9My0+Vz5YBPba3ARV3fWcc=";
})
] ++ lib.optional (stdenv.hostPlatform != stdenv.buildPlatform) ./clang-cross.patch;
separateDebugInfo = true;
# postPatch = "patchShebangs .";
configurePhase = ''
export KCONFIG_NOTIMESTAMP=1
make ${if enableMinimal then "allnoconfig" else "defconfig"}
${configParser}
cat << EOF | parseconfig
CONFIG_PREFIX "$out"
CONFIG_INSTALL_NO_USR y
CONFIG_LFS y
# More features for modprobe.
${lib.optionalString (!enableMinimal) ''
CONFIG_FEATURE_MODPROBE_BLACKLIST y
CONFIG_FEATURE_MODUTILS_ALIAS y
CONFIG_FEATURE_MODUTILS_SYMBOLS y
CONFIG_MODPROBE_SMALL n
''}
${lib.optionalString enableStatic ''
CONFIG_STATIC y
''}
${lib.optionalString (!enableAppletSymlinks) ''
CONFIG_INSTALL_APPLET_DONT y
CONFIG_INSTALL_APPLET_SYMLINKS n
''}
# Use the external mount.cifs program.
CONFIG_FEATURE_MOUNT_CIFS n
CONFIG_FEATURE_MOUNT_HELPERS y
# BB_SHADOW
FEATURE_SHADOWPASSWDS y
CONFIG_USE_BB_PWD_GRP y
CONFIG_USE_BB_SHADOW y
CONFIG_USE_BB_CRYPT y
USE_BB_CRYPT_SHA y
CONFIG_FEATURE_DEFAULT_PASSWD_ALGO "sha512"
# Set paths for console fonts.
CONFIG_DEFAULT_SETFONT_DIR "/etc/kbd"
# Bump from 4KB, much faster I/O
CONFIG_FEATURE_COPYBUF_KB 64
# Doesn't build with current kernel headers.
# https://bugs.busybox.net/show_bug.cgi?id=15934
CONFIG_TC n
# Set the path for the udhcpc script
CONFIG_UDHCPC_DEFAULT_SCRIPT "/usr/share/busybox/"
${extraConfig}
CONFIG_CROSS_COMPILER_PREFIX "${stdenv.cc.targetPrefix}"
${libcConfig}
EOF
make oldconfig
runHook postConfigure
'';
postConfigure = lib.optionalString (useMusl && stdenv.hostPlatform.libc != "musl") ''
makeFlagsArray+=("CC=${stdenv.cc.targetPrefix}cc -isystem ${musl.dev}/include -B${musl}/lib -L${musl}/lib")
'';
makeFlags = [ "SKIP_STRIP=y" ];
strictDeps = true;
depsBuildBuild = [ buildPackages.stdenv.cc ];
buildInputs = lib.optionals (enableStatic && !useMusl && stdenv.cc.libc ? static) [
stdenv.cc.libc
stdenv.cc.libc.static
];
enableParallelBuilding = true;
doCheck = false; # tries to access the net
passthru.shellPath = "/bin/ash";
meta = with lib; {
description = "Tiny versions of common UNIX utilities in a single small executable";
homepage = "https://busybox.net/";
license = licenses.gpl2Only;
maintainers = with maintainers; [
TethysSvensson
qyliss
];
platforms = platforms.linux;
priority = 15; # below systemd (halt, init, poweroff, reboot) and coreutils
};
}

17
pkgs/cert/default.nix Normal file
View file

@ -0,0 +1,17 @@
{
runCommand,
pkgs,
}:
runCommand "patagia-certs"
{
buildInputs = with pkgs; [
openssl
];
}
''
mkdir -pv $out
openssl req -new -x509 -days 365 -nodes -out $out/cert.pem -keyout $out/key.pem -subj "/CN=patagia-signing"
''

View file

@ -0,0 +1,49 @@
{
stdenv,
pkgs,
...
}:
stdenv.mkDerivation (finalAttrs: {
pname = "dbus-broker";
version = pkgs.dbus-broker.version;
src = pkgs.dbus-broker.src;
nativeBuildInputs = pkgs.dbus-broker.nativeBuildInputs;
buildInputs = pkgs.dbus-broker.buildInputs;
mesonFlags = [
# while we technically support 4.9 and 4.14, the NixOS module will throw an
# error when using a kernel that's too old
"--prefix=/"
"--bindir=/usr/bin"
"-D=linux-4-17=true"
"-D=system-console-users=gdm,sddm,lightdm"
];
PKG_CONFIG_SYSTEMD_SYSTEMDSYSTEMUNITDIR = "/usr/lib/systemd/system";
PKG_CONFIG_SYSTEMD_SYSTEMDUSERUNITDIR = "/usr/lib/systemd/user";
PKG_CONFIG_SYSTEMD_CATALOGDIR = "/usr/lib/systemd/catalog";
preInstall = ''
export DESTDIR=${placeholder "out"}
'';
postInstall = ''
mkdir -p $out/usr/share
cp -Pr ${pkgs.dbus.out}/share/* $out/usr/share/
cp ${pkgs.dbus.out}/etc/systemd/system/dbus.socket $out/usr/lib/systemd/system/
mv $out/usr/lib/systemd/system/dbus-broker.service $out/usr/lib/systemd/system/dbus.service
find $out/usr/share/ -type d -exec chmod 755 {} \;
sed -i 's#/nix/store.*/share#/usr/share#' $out/usr/share/xml/dbus-1/catalog.xml
sed -i 's#/nix/store.*/libexec#/usr/bin#' $out/usr/share/dbus-1/system.conf
mkdir -p $out/usr/lib/sysusers.d/
echo 'u! messagebus - "DBus broker"' > $out/usr/lib/sysusers.d/dbus-broker.conf
'';
doCheck = false;
meta = pkgs.dbus-broker.meta;
})

54
pkgs/glibc/default.nix Normal file
View file

@ -0,0 +1,54 @@
{
pkgs,
stdenv,
...
}:
let
version = pkgs.glibc.version;
src = pkgs.glibc.src;
pname = pkgs.glibc.pname;
in
stdenv.mkDerivation (finalAttrs: {
inherit version;
inherit src;
inherit pname;
enableParallelBuilding = true;
dontPatchShebangs = true;
configureFlags = [
"--prefix=/"
"--libdir=/lib"
"--bindir=/bin"
"--sysconfdir=/etc"
];
preConfigure =
''
export PWD_P=$(type -tP pwd)
for i in configure io/ftwtest-sh; do
sed -i "$i" -e "s^/bin/pwd^$PWD_P^g"
done
mkdir ../build
cd ../build
configureScript="`pwd`/../$sourceRoot/configure"
'';
nativeBuildInputs = with pkgs; [
bison
python3Minimal
];
outputs = [
"out"
];
preInstall = ''
export DESTDIR=${placeholder "out"}
'';
meta = pkgs.glibc.meta;
})

285
pkgs/image/default.nix Normal file
View file

@ -0,0 +1,285 @@
{
lib,
stdenv,
pkgs,
version,
runCommand,
updateUrl,
microcode ? "",
secureBoot ? "false",
arch,
...
}:
let
pname = "patos-image";
in
runCommand pname {
versionString = "${version}-"+ arch.${stdenv.hostPlatform.system};
mcode = lib.optionalString (microcode == "amd") "--microcode ${pkgs.microcode-amd}/amd-ucode.img"
+ lib.optionalString (microcode == "intel") "--microcode ${pkgs.microcode-intel}/intel-ucode.img";
# aarch64 doesn't support compressed kernel images
kernelImage = lib.optionalString (stdenv.hostPlatform.isAarch64 == true) "Image"
+ lib.optionalString (stdenv.hostPlatform.isx86_64 == true) "bzImage";
nativeBuildInputs = with pkgs; [
erofs-utils
dosfstools
mtools
jq
];
env = {
# vfat options won't efi won't find the fs otherwise.
SYSTEMD_REPART_MKFS_OPTIONS_VFAT = "-S 512 -c";
SYSTEMD_REPART_MKFS_OPTIONS_EROFS = "--all-root -zlz4hc,12 -C1048576 -Efragments,dedupe,ztailpacking";
};
kernelCmdLine = "systemd.journald.forward_to_console=1 console=ttyS0 patos.secureboot=${secureBoot}";
}
''
set -ex -o pipefail
mkdir -p $out/init.repart.d $out/final.repart.d
pushd $out
mkdir rootfs
cp -prP ${pkgs.patos.rootfs}/* rootfs/
find rootfs/ -type d -exec chmod 755 {} \;
# set default target to multi-user
ln -sf multi-user.target rootfs/usr/lib/systemd/system/default.target
# enable dbus
ln -sf ../dbus.service rootfs/usr/lib/systemd/system/multi-user.target.wants/dbus.service
ln -sf ../dbus.socket rootfs/usr/lib/systemd/system/sockets.target.wants/dbus.socket
# enable network services
ln -sf ../systemd-networkd.service rootfs/usr/lib/systemd/system/sysinit.target.wants/systemd-networkd.service
ln -sf ../systemd-resolved.service rootfs/usr/lib/systemd/system/sysinit.target.wants/systemd-resolved.service
ln -sf ../systemd-timesyncd.service rootfs/usr/lib/systemd/system/multi-user.target.wants/systemd-timesyncd.service
# enable default network config
mv rootfs/usr/lib/systemd/network/89-ethernet.network.example rootfs/usr/lib/systemd/network/89-ethernet.network
# enable confext/sysext services
ln -sf ../systemd-confext.service rootfs/usr/lib/systemd/system/sysinit.target.wants/systemd-confext.service
ln -sf ../systemd-sysext.service rootfs/usr/lib/systemd/system/sysinit.target.wants/systemd-sysext.service
cat <<EOF > rootfs/usr/lib/systemd/system/secure-boot-import-keys.service
[Unit]
Description=Import Secure Boot keys
DefaultDependencies=no
RequiresMountsFor=/var/lib/sbctl /boot
ConditionPathExists=/boot/sbctl/keys
After=local-fs.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=sbctl import-keys -d /boot/sbctl/keys
ExecStartPost=rm -rf /boot/sbctl
EOF
ln -sf ../secure-boot-import-keys.service rootfs/usr/lib/systemd/system/sysinit.target.wants/secure-boot-import-keys.service
# forked from flatcar https://github.com/flatcar/init/blob/flatcar-master/systemd/system/ensure-sysext.service
cat <<EOF > rootfs/usr/lib/systemd/system/ensure-sysext.service
[Unit]
BindsTo=systemd-sysext.service
After=systemd-sysext.service
DefaultDependencies=no
ConditionDirectoryNotEmpty=|/etc/extensions
ConditionDirectoryNotEmpty=|/run/extensions
ConditionDirectoryNotEmpty=|/var/lib/extensions
ConditionDirectoryNotEmpty=|/usr/local/lib/extensions
ConditionDirectoryNotEmpty=|/usr/lib/extensions
ConditionPathExists=!/etc/initrd-release
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/systemctl daemon-reload
ExecStart=/usr/bin/systemctl restart --no-block sockets.target timers.target multi-user.target
[Install]
WantedBy=sysinit.target
EOF
ln -sf ../ensure-sysext.service rootfs/usr/lib/systemd/system/sysinit.target.wants/ensure-sysext.service
# sysupdate
mkdir -p rootfs/etc/sysupdate.d
cat <<EOF > rootfs/etc/sysupdate.d/10-uki.transfer
[Source]
Path=${updateUrl}
MatchPattern=patos_@v-%a.efi
Type=url-file
[Target]
InstancesMax=2
MatchPattern=patos_@v-%a+@l-@d.efi patos_@v-%a+@l.efi patos_@v-%a.efi
Mode=0444
Path=/EFI/Linux
PathRelativeTo=esp
TriesDone=0
TriesLeft=3
Type=regular-file
[Transfer]
Verify=no
EOF
cat <<EOF > rootfs/etc/sysupdate.d/20-root-verity.transfer
[Source]
Type=url-file
Path=${updateUrl}
MatchPattern=patos_@v-%a_@u.verity
[Target]
Type=partition
Path=auto
MatchPattern=verity-@v
MatchPartitionType=root-verity
ReadOnly=1
[Transfer]
Verify=no
EOF
cat <<EOF > rootfs/etc/sysupdate.d/22-root.transfer
[Source]
Type=url-file
Path=${updateUrl}
MatchPattern=patos_@v-%a_@u.root
[Target]
Type=partition
Path=auto
MatchPattern=root-@v
MatchPartitionType=root
ReadOnly=1
[Transfer]
Verify=no
EOF
# Initial partitioning
cat <<EOF > init.repart.d/10-root.conf
[Partition]
Type=root
Format=erofs
Minimize=best
AddValidateFS=false
CopyFiles=/rootfs:/
Verity=data
VerityMatchKey=root
SplitName=root
EOF
cat <<EOF > init.repart.d/20-root-verity.conf
[Partition]
Type=root-verity
Verity=hash
VerityMatchKey=root
AddValidateFS=false
Minimize=best
SplitName=verity
EOF
#TODO: Add verity signature partition
${pkgs.patos.systemd}/usr/bin/systemd-repart \
--no-pager \
--empty=create \
--size=auto \
--definitions=$out/init.repart.d \
--split=true \
--json=pretty \
--root=$out \
patos_$versionString.raw > init-repart-output.json
rm -f patos_$versionString.raw
roothash=$(jq -r '.[0].roothash' init-repart-output.json)
rootPart=$(jq -r '.[0].split_path' init-repart-output.json)
rootUuid=$(jq -r '.[0].uuid' init-repart-output.json)
verityPart=$(jq -r '.[1].split_path' init-repart-output.json)
verityUuid=$(jq -r '.[1].uuid' init-repart-output.json)
ln -sf patos_$versionString.verity.raw patos_"$versionString"_"$verityUuid".verity
ln -sf patos_$versionString.root.raw patos_"$versionString"_"$rootUuid".root
${pkgs.patos.systemd}/usr/bin/ukify build \
--linux ${pkgs.patos.kernel}/$kernelImage \
--initrd ${pkgs.patos.initrd}/initrd.xz \
$mcode \
--os-release @rootfs/etc/os-release \
--cmdline "$kernelCmdLine roothash=$roothash" \
-o patos_$versionString.efi
# install ESP
SYSTEMD_RELAX_ESP_CHECKS=1 ${pkgs.patos.systemd}/usr/bin/bootctl install --root ./rootfs --esp-path /boot
# setup factory reset
mkdir -p rootfs/boot/EFI/tools
cp ${pkgs.edk2-uefi-shell}/shell.efi rootfs/boot/EFI/tools/
cat <<EOF > rootfs/boot/EFI/tools/factoryreset.nsh
setvar FactoryReset -guid 8cf2644b-4b0b-428f-9387-6d876050dc67 -nv -rt =%1
reset
EOF
cat <<EOF > rootfs/boot/loader/entries/factoryreset.conf
title Enable Factory Reset
options -nostartup -nomap
options \EFI\tools\factoryreset.nsh L"t"
efi EFI/tools/shell.efi
EOF
echo "timeout 2" > rootfs/boot/loader/loader.conf
# install UKI
cp patos_$versionString.efi rootfs/boot/EFI/Linux
# Final partitioning
cat <<EOF > final.repart.d/10-esp.conf
[Partition]
Type=esp
Format=vfat
SizeMinBytes=256M
SizeMaxBytes=256M
CopyFiles=$out/rootfs/boot:/
EOF
cat <<EOF > final.repart.d/20-root.conf
[Partition]
Type=root
Label=root-${version}
CopyBlocks=$out/$rootPart
UUID=$rootUuid
SizeMinBytes=64M
SizeMaxBytes=64M
ReadOnly=1
EOF
cat <<EOF > final.repart.d/22-root-verity.conf
[Partition]
Type=root-verity
Label=verity-${version}
CopyBlocks=$out/$verityPart
UUID=$verityUuid
ReadOnly=1
EOF
# finalize image ready for boot
${pkgs.patos.systemd}/usr/bin/systemd-repart \
--no-pager \
--empty=create \
--size=auto \
--definitions=./final.repart.d \
patos_$versionString.img > final-repart-output.json
rm -rf rootfs init.repart.d final.repart.d *.json
sha256sum *.root *.verity *.efi *.tar.xz > SHA256SUMS
popd
''

17
pkgs/kernel/default.nix Normal file
View file

@ -0,0 +1,17 @@
{ pkgs, lib, stdenv }:
let
version = "6.15.7";
hash = "sha256-NQfdEFsKDhEBvUPSlEcvzPhTQpolml+nxnRnu6MY+Ok=";
arch = lib.optionalString (stdenv.hostPlatform.isAarch64 == true) "arm64"
+ lib.optionalString (stdenv.hostPlatform.isx86_64 == true) "x86_64";
in
(pkgs.callPackage ./manual-config.nix { }) {
version = "${version}-patos1";
modDirVersion = version;
src = pkgs.fetchurl {
url = "https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${version}.tar.xz";
hash = hash;
};
configfile = ./generic-${arch}.config;
allowImportFromDerivation = true;
}

File diff suppressed because it is too large Load diff

View file

@ -276,7 +276,7 @@ CONFIG_BRIDGE_VLAN_FILTERING=y
CONFIG_BRIDGE=y
CONFIG_BSD_DISKLABEL=y
CONFIG_BSD_PROCESS_ACCT=y
CONFIG_BTRFS_FS=m
CONFIG_BTRFS_FS=y
CONFIG_BTRFS_FS_POSIX_ACL=y
CONFIG_BUFFER_HEAD=y
CONFIG_BUG_ON_DATA_CORRUPTION=y
@ -426,7 +426,7 @@ CONFIG_CRYPTO_ARCH_HAVE_LIB_CHACHA=y
CONFIG_CRYPTO_ARCH_HAVE_LIB_CURVE25519=y
CONFIG_CRYPTO_ARCH_HAVE_LIB_POLY1305=y
CONFIG_CRYPTO_AUTHENC=y
CONFIG_CRYPTO_BLAKE2B=m
CONFIG_CRYPTO_BLAKE2B=y
CONFIG_CRYPTO_BLAKE2S_X86=y
CONFIG_CRYPTO_CBC=y
CONFIG_CRYPTO_CCM=y
@ -522,11 +522,7 @@ CONFIG_DEBUG_BUGVERBOSE=y
CONFIG_DEBUG_ENTRY=y
CONFIG_DEBUG_FS_ALLOW_ALL=y
CONFIG_DEBUG_FS=y
CONFIG_DEBUG_INFO_BTF_MODULES=y
CONFIG_DEBUG_INFO_BTF=y
CONFIG_DEBUG_INFO_COMPRESSED_NONE=y
CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
CONFIG_DEBUG_INFO=y
CONFIG_DEBUG_INFO=n
CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_LIST=y
CONFIG_DEBUG_MISC=y
@ -591,7 +587,8 @@ CONFIG_DM_SWITCH=m
CONFIG_DM_THIN_PROVISIONING=m
CONFIG_DM_UNSTRIPED=m
CONFIG_DM_VDO=m
CONFIG_DM_VERITY=m
CONFIG_DM_VERITY=y
CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y
CONFIG_DM_WRITECACHE=m
CONFIG_DM_ZERO=y
CONFIG_DM_ZONED=m
@ -646,7 +643,7 @@ CONFIG_ELF_CORE=y
CONFIG_ELFCORE=y
CONFIG_ENA_ETHERNET=y
CONFIG_ENCLOSURE_SERVICES=y
CONFIG_ENCRYPTED_KEYS=m
CONFIG_ENCRYPTED_KEYS=y
CONFIG_ENIC=m
CONFIG_EPOLL=y
CONFIG_EROFS_FS_POSIX_ACL=y
@ -1395,18 +1392,15 @@ CONFIG_MMU_LAZY_TLB_REFCOUNT=y
CONFIG_MMU_NOTIFIER=y
CONFIG_MMU=y
CONFIG_MODPROBE_PATH="/sbin/modprobe"
CONFIG_MODULE_COMPRESS=y
CONFIG_MODULE_COMPRESS_ALL=y
CONFIG_MODULE_COMPRESS_ZSTD=y
CONFIG_MODULE_FORCE_UNLOAD=y
CONFIG_MODULE_SIG_ALL=y
CONFIG_MODULE_SIG_FORCE=y
CONFIG_MODULE_SIG_FORMAT=y
CONFIG_MODULE_SIG_HASH="sha512"
CONFIG_MODULE_SIG_KEY="certs/signing_key.pem"
CONFIG_MODULE_SIG_KEY_TYPE_RSA=y
CONFIG_MODULE_SIG_SHA512=y
CONFIG_MODULE_SIG=y
CONFIG_MODULE_SRCVERSION_ALL=y
CONFIG_MODULE_UNLOAD=y
CONFIG_MODULE_SIG=y
CONFIG_MODULE_SIG_FORCE=y
CONFIG_MODULE_SIG_ALL=y
CONFIG_MODULES_TREE_LOOKUP=y
CONFIG_MODULES_USE_ELF_RELA=y
CONFIG_MODULES=y
@ -1961,7 +1955,7 @@ CONFIG_QUOTA_TREE=y
CONFIG_QUOTA=y
CONFIG_R8169=m
CONFIG_RAID6_PQ_BENCHMARK=y
CONFIG_RAID6_PQ=m
CONFIG_RAID6_PQ=y
CONFIG_RAID_ATTRS=y
CONFIG_RANDOMIZE_BASE=y
CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT=y
@ -2221,6 +2215,7 @@ CONFIG_TCG_CRB=y
CONFIG_TCG_TIS_CORE=y
CONFIG_TCG_TIS=y
CONFIG_TCG_TPM=y
CONFIG_TCG_TPM2_HMAC=n
CONFIG_TCP_CONG_ADVANCED=y
CONFIG_TCP_CONG_BBR=y
CONFIG_TCP_CONG_CUBIC=y
@ -2494,7 +2489,7 @@ CONFIG_XFS_QUOTA=y
CONFIG_XFS_RT=y
CONFIG_XFS_SUPPORT_ASCII_CI=y
CONFIG_XFS_SUPPORT_V4=y
CONFIG_XOR_BLOCKS=m
CONFIG_XOR_BLOCKS=y
CONFIG_XPS=y
CONFIG_XXHASH=y
CONFIG_XZ_DEC_ARMTHUMB=y

View file

@ -0,0 +1,594 @@
{
lib,
stdenv,
buildPackages,
runCommand,
nettools,
bc,
bison,
flex,
perl,
rsync,
gmp,
libmpc,
mpfr,
openssl,
cpio,
elfutils,
hexdump,
zstd,
python3Minimal,
zlib,
pahole,
kmod,
ubootTools,
erofs-utils,
cryptsetup,
fetchpatch,
rustc,
rust-bindgen,
rustPlatform,
}:
let
lib_ = lib;
stdenv_ = stdenv;
readConfig =
configfile:
import
(runCommand "config.nix" { } ''
echo "{" > "$out"
while IFS='=' read key val; do
[ "x''${key#CONFIG_}" != "x$key" ] || continue
no_firstquote="''${val#\"}";
echo ' "'"$key"'" = "'"''${no_firstquote%\"}"'";' >> "$out"
done < "${configfile}"
echo "}" >> $out
'').outPath;
in
lib.makeOverridable (
{
# The kernel version
version,
# The kernel pname (should be set for variants)
pname ? "linux",
# Position of the Linux build expression
pos ? null,
# Additional kernel make flags
extraMakeFlags ? [ ],
# The name of the kernel module directory
# Needs to be X.Y.Z[-extra], so pad with zeros if needed.
modDirVersion ? null, # derive from version
# The kernel source (tarball, git checkout, etc.)
src,
# a list of { name=..., patch=..., extraConfig=...} patches
kernelPatches ? [ ],
# The kernel .config file
configfile,
# Manually specified nixexpr representing the config
# If unspecified, this will be autodetected from the .config
config ? lib.optionalAttrs allowImportFromDerivation (readConfig configfile),
# Custom seed used for CONFIG_GCC_PLUGIN_RANDSTRUCT if enabled. This is
# automatically extended with extra per-version and per-config values.
randstructSeed ? "",
# Extra meta attributes
extraMeta ? { },
# for module compatibility
isZen ? false,
isLibre ? false,
isHardened ? false,
# Whether to utilize the controversial import-from-derivation feature to parse the config
allowImportFromDerivation ? false,
# ignored
features ? null,
lib ? lib_,
stdenv ? stdenv_,
}:
let
# Provide defaults. Note that we support `null` so that callers don't need to use optionalAttrs,
# which can lead to unnecessary strictness and infinite recursions.
modDirVersion_ = if modDirVersion == null then lib.versions.pad 3 version else modDirVersion;
in
let
# Shadow the un-defaulted parameter; don't want null.
modDirVersion = modDirVersion_;
inherit (lib)
hasAttr
getAttr
optional
optionals
optionalString
optionalAttrs
maintainers
platforms
;
drvAttrs =
config_: kernelConf: kernelPatches: configfile:
let
# Folding in `ubootTools` in the default nativeBuildInputs is problematic, as
# it makes updating U-Boot cumbersome, since it will go above the current
# threshold of rebuilds
#
# To prevent these needless rounds of staging for U-Boot builds, we can
# limit the inclusion of ubootTools to target platforms where uImage *may*
# be produced.
#
# This command lists those (kernel-named) platforms:
# .../linux $ grep -l uImage ./arch/*/Makefile | cut -d'/' -f3 | sort
#
# This is still a guesstimation, but since none of our cached platforms
# coincide in that list, this gives us "perfect" decoupling here.
linuxPlatformsUsingUImage = [
"arc"
"arm"
"csky"
"mips"
"powerpc"
"sh"
"sparc"
"xtensa"
];
needsUbootTools = lib.elem stdenv.hostPlatform.linuxArch linuxPlatformsUsingUImage;
config =
let
attrName = attr: "CONFIG_" + attr;
in
{
isSet = attr: hasAttr (attrName attr) config;
getValue = attr: if config.isSet attr then getAttr (attrName attr) config else null;
isYes = attr: (config.getValue attr) == "y";
isNo = attr: (config.getValue attr) == "n";
isModule = attr: (config.getValue attr) == "m";
isEnabled = attr: (config.isModule attr) || (config.isYes attr);
isDisabled = attr: (!(config.isSet attr)) || (config.isNo attr);
}
// config_;
isModular = config.isYes "MODULES";
withRust = config.isYes "RUST";
buildDTBs = kernelConf.DTB or false;
# Dependencies that are required to build kernel modules
moduleBuildDependencies =
[
pahole
perl
elfutils
# module makefiles often run uname commands to find out the kernel version
(buildPackages.deterministic-uname.override { inherit modDirVersion; })
]
++ optional (lib.versionAtLeast version "5.13") zstd
++ optionals withRust [
rustc
rust-bindgen
];
in
(optionalAttrs isModular {
outputs = [
"out"
"dev"
];
})
// {
passthru = rec {
inherit
version
modDirVersion
config
kernelPatches
configfile
moduleBuildDependencies
stdenv
;
inherit
isZen
isHardened
isLibre
withRust
;
isXen = lib.warn "The isXen attribute is deprecated. All Nixpkgs kernels that support it now have Xen enabled." true;
baseVersion = lib.head (lib.splitString "-rc" version);
kernelOlder = lib.versionOlder baseVersion;
kernelAtLeast = lib.versionAtLeast baseVersion;
};
inherit src;
depsBuildBuild = [ buildPackages.stdenv.cc ];
nativeBuildInputs =
[
bison
flex
perl
bc
nettools
openssl
rsync
gmp
libmpc
mpfr
elfutils
zstd
python3Minimal
kmod
hexdump
erofs-utils
cryptsetup
]
++ optional needsUbootTools ubootTools
++ optionals (lib.versionAtLeast version "5.2") [
cpio
pahole
zlib
]
++ optionals withRust [
rustc
rust-bindgen
];
RUST_LIB_SRC = lib.optionalString withRust rustPlatform.rustLibSrc;
# avoid leaking Rust source file names into the final binary, which adds
# a false dependency on rust-lib-src on targets with uncompressed kernels
KRUSTFLAGS = lib.optionalString withRust "--remap-path-prefix ${rustPlatform.rustLibSrc}=/";
# patches =
# map (p: p.patch) kernelPatches
# # Required for deterministic builds along with some postPatch magic.
# ++ optional (lib.versionOlder version "5.19") ./randstruct-provide-seed.patch
# ++ optional (lib.versionAtLeast version "5.19") ./randstruct-provide-seed-5.19.patch
# # Linux 5.12 marked certain PowerPC-only symbols as GPL, which breaks
# # OpenZFS; this was fixed in Linux 5.19 so we backport the fix
# # https://github.com/openzfs/zfs/pull/13367
# ++ optional (lib.versionAtLeast version "5.12" &&
# lib.versionOlder version "5.19" &&
# stdenv.hostPlatform.isPower)
# (fetchpatch {
# url = "https://git.kernel.org/pub/scm/linux/kernel/git/powerpc/linux.git/patch/?id=d9e5c3e9e75162f845880535957b7fd0b4637d23";
# hash = "sha256-bBOyJcP6jUvozFJU0SPTOf3cmnTQ6ZZ4PlHjiniHXLU=";
# });
postPatch = ''
# Ensure that depmod gets resolved through PATH
sed -i Makefile -e 's|= /sbin/depmod|= depmod|'
# Some linux-hardened patches now remove certain files in the scripts directory, so the file may not exist.
[[ -f scripts/ld-version.sh ]] && patchShebangs scripts/ld-version.sh
# Set randstruct seed to a deterministic but diversified value. Note:
# we could have instead patched gen-random-seed.sh to take input from
# the buildFlags, but that would require also patching the kernel's
# toplevel Makefile to add a variable export. This would be likely to
# cause future patch conflicts.
# for file in scripts/gen-randstruct-seed.sh scripts/gcc-plugins/gen-random-seed.sh; do
# if [ -f "$file" ]; then
# substituteInPlace "$file" \
# --replace NIXOS_RANDSTRUCT_SEED \
# $(echo ${randstructSeed}${src} ${placeholder "configfile"} | sha256sum | cut -d ' ' -f 1 | tr -d '\n')
# break
# fi
# done
patchShebangs scripts
# also patch arch-specific install scripts
for i in $(find arch -name install.sh); do
patchShebangs "$i"
done
# unset $src because the build system tries to use it and spams a bunch of warnings
# see: https://github.com/torvalds/linux/commit/b1992c3772e69a6fd0e3fc81cd4d2820c8b6eca0
unset src
'';
configurePhase = ''
runHook preConfigure
mkdir build
export buildRoot="$(pwd)/build"
echo "manual-config configurePhase buildRoot=$buildRoot pwd=$PWD"
if [ -f "$buildRoot/.config" ]; then
echo "Could not link $buildRoot/.config : file exists"
exit 1
fi
ln -sv ${configfile} $buildRoot/.config
# reads the existing .config file and prompts the user for options in
# the current kernel source that are not found in the file.
make $makeFlags "''${makeFlagsArray[@]}" oldconfig
runHook postConfigure
make $makeFlags "''${makeFlagsArray[@]}" prepare
actualModDirVersion="$(cat $buildRoot/include/config/kernel.release)"
if [ "$actualModDirVersion" != "${modDirVersion}" ]; then
echo "Error: modDirVersion ${modDirVersion} specified in the Nix expression is wrong, it should be: $actualModDirVersion"
exit 1
fi
buildFlagsArray+=("KBUILD_BUILD_TIMESTAMP=$(date -u -d @$SOURCE_DATE_EPOCH)")
cd $buildRoot
'';
buildFlags =
[
"KBUILD_BUILD_VERSION=1-PatOS"
kernelConf.target
"vmlinux" # for "perf" and things like that
]
++ optional isModular "modules"
++ optionals buildDTBs [
"dtbs"
"DTC_FLAGS=-@"
]
++ extraMakeFlags;
installFlags =
[
"INSTALL_PATH=$(out)"
]
++ (optional isModular "INSTALL_MOD_PATH=$(out)")
++ optionals buildDTBs [
"dtbs_install"
"INSTALL_DTBS_PATH=$(out)/dtbs"
];
dontStrip = true;
preInstall =
let
# All we really need to do here is copy the final image and System.map to $out,
# and use the kernel's modules_install, firmware_install, dtbs_install, etc. targets
# for the rest. Easy, right?
#
# Unfortunately for us, the obvious way of getting the built image path,
# make -s image_name, does not work correctly, because some architectures
# (*cough* aarch64 *cough*) change KBUILD_IMAGE on the fly in their install targets,
# so we end up attempting to install the thing we didn't actually build.
#
# Thankfully, there's a way out that doesn't involve just hardcoding everything.
#
# The kernel has an install target, which runs a pretty simple shell script
# (located at scripts/install.sh or arch/$arch/boot/install.sh, depending on
# which kernel version you're looking at) that tries to do something sensible.
#
# (it would be great to hijack this script immediately, as it has all the
# information we need passed to it and we don't need it to try and be smart,
# but unfortunately, the exact location of the scripts differs between kernel
# versions, and they're seemingly not considered to be public API at all)
#
# One of the ways it tries to discover what "something sensible" actually is
# is by delegating to what's supposed to be a user-provided install script
# located at ~/bin/installkernel.
#
# (the other options are:
# - a distribution-specific script at /sbin/installkernel,
# which we can't really create in the sandbox easily
# - an architecture-specific script at arch/$arch/boot/install.sh,
# which attempts to guess _something_ and usually guesses very wrong)
#
# More specifically, the install script exec's into ~/bin/installkernel, if one
# exists, with the following arguments:
#
# $1: $KERNELRELEASE - full kernel version string
# $2: $KBUILD_IMAGE - the final image path
# $3: System.map - path to System.map file, seemingly hardcoded everywhere
# $4: $INSTALL_PATH - path to the destination directory as specified in installFlags
#
# $2 is exactly what we want, so hijack the script and use the knowledge given to it
# by the makefile overlords for our own nefarious ends.
#
# Note that the makefiles specifically look in ~/bin/installkernel, and
# writeShellScriptBin writes the script to <store path>/bin/installkernel,
# so HOME needs to be set to just the store path.
#
# FIXME: figure out a less roundabout way of doing this.
installkernel = buildPackages.writeShellScriptBin "installkernel" ''
cp -av $2 $4
cp -av $3 $4
'';
in
''
installFlagsArray+=("-j$NIX_BUILD_CORES")
export HOME=${installkernel}
'';
# Some image types need special install targets (e.g. uImage is installed with make uinstall on arm)
installTargets = [
(kernelConf.installTarget or (
if kernelConf.target == "uImage" && stdenv.hostPlatform.linuxArch == "arm" then
"uinstall"
else if
kernelConf.target == "zImage"
|| kernelConf.target == "Image.gz"
|| kernelConf.target == "vmlinuz.efi"
then
"zinstall"
else
"install"
)
)
];
# We remove a bunch of stuff that is symlinked from other places to save space,
# which trips the broken symlink check. So, just skip it. We'll know if it explodes.
dontCheckForBrokenSymlinks = true;
postInstall = optionalString isModular ''
mkdir -p $dev
cp vmlinux $dev/
# if [ -z "''${dontStrip-}" ]; then
# installFlagsArray+=("INSTALL_MOD_STRIP=1")
# fi
make modules_install $makeFlags "''${makeFlagsArray[@]}" \
$installFlags "''${installFlagsArray[@]}"
unlink $out/lib/modules/${modDirVersion}/build
rm -f $out/lib/modules/${modDirVersion}/source
mkdir -p $dev/lib/modules/${modDirVersion}/{build,source}
# To save space, exclude a bunch of unneeded stuff when copying.
(cd .. && rsync --archive --prune-empty-dirs \
--exclude='/build/' \
* $dev/lib/modules/${modDirVersion}/source/)
cd $dev/lib/modules/${modDirVersion}/source
cp $buildRoot/{.config,Module.symvers} $dev/lib/modules/${modDirVersion}/build
make modules_prepare $makeFlags "''${makeFlagsArray[@]}" O=$dev/lib/modules/${modDirVersion}/build
# For reproducibility, removes accidental leftovers from a `cc1` call
# from a `try-run` call from the Makefile
rm -f $dev/lib/modules/${modDirVersion}/build/.[0-9]*.d
# Keep some extra files on some arches (powerpc, aarch64)
for f in arch/powerpc/lib/crtsavres.o arch/arm64/kernel/ftrace-mod.o; do
if [ -f "$buildRoot/$f" ]; then
cp $buildRoot/$f $dev/lib/modules/${modDirVersion}/build/$f
fi
done
# !!! No documentation on how much of the source tree must be kept
# If/when kernel builds fail due to missing files, you can add
# them here. Note that we may see packages requiring headers
# from drivers/ in the future; it adds 50M to keep all of its
# headers on 3.10 though.
chmod u+w -R ..
arch=$(cd $dev/lib/modules/${modDirVersion}/build/arch; ls)
# Remove unused arches
for d in $(cd arch/; ls); do
if [ "$d" = "$arch" ]; then continue; fi
if [ "$arch" = arm64 ] && [ "$d" = arm ]; then continue; fi
rm -rf arch/$d
done
# Remove all driver-specific code (50M of which is headers)
rm -fR drivers
# Keep all headers
find . -type f -name '*.h' -print0 | xargs -0 -r chmod u-w
# Keep linker scripts (they are required for out-of-tree modules on aarch64)
find . -type f -name '*.lds' -print0 | xargs -0 -r chmod u-w
# Keep root and arch-specific Makefiles
chmod u-w Makefile arch/"$arch"/Makefile*
# Keep whole scripts dir
chmod u-w -R scripts
# Delete everything not kept
find . -type f -perm -u=w -print0 | xargs -0 -r rm
# Delete empty directories
find -empty -type d -delete
pkgName="patos-kernel-modules"
mkdir -p $out/tree/usr/lib/extension-release.d
cat << EOF > $out/tree/usr/lib/extension-release.d/extension-release.$pkgName
ID=patos
IMAGE_ID=$pkgName
IMAGE_VERSION=${version}
VERSION_ID=patos
EOF
cp -Prp $out/lib/modules $out/tree/usr/lib/modules
find $out/tree -type d -exec chmod 0755 {} \;
mkfs.erofs --all-root -zlz4hc,12 -C1048576 -Efragments,dedupe,ztailpacking $out/$pkgName.raw $out/tree/
veritysetup format --root-hash-file $out/$pkgName.roothash $out/$pkgName.raw $out/$pkgName.verity
chmod -R 755 $out/tree && rm -rf $out/tree
'';
requiredSystemFeatures = [ "big-parallel" ];
meta = {
# https://github.com/NixOS/nixpkgs/pull/345534#issuecomment-2391238381
broken = withRust && lib.versionOlder version "6.12";
description =
"The Linux kernel"
+ (
if kernelPatches == [ ] then
""
else
" (with patches: " + lib.concatStringsSep ", " (map (x: x.name) kernelPatches) + ")"
);
license = lib.licenses.gpl2Only;
homepage = "https://www.kernel.org/";
maintainers = lib.teams.linux-kernel.members ++ [
maintainers.thoughtpolice
];
platforms = platforms.linux;
badPlatforms =
lib.optionals (lib.versionOlder version "4.15") [
"riscv32-linux"
"riscv64-linux"
]
++ lib.optional (lib.versionOlder version "5.19") "loongarch64-linux";
timeout = 14400; # 4 hours
} // extraMeta;
};
# Absolute paths for compilers avoid any PATH-clobbering issues.
commonMakeFlags =
[
"ARCH=${stdenv.hostPlatform.linuxArch}"
"CROSS_COMPILE=${stdenv.cc.targetPrefix}"
]
++ lib.optionals (stdenv.isx86_64 && stdenv.cc.bintools.isLLVM) [
# The wrapper for ld.lld breaks linking the kernel. We use the
# unwrapped linker as workaround. See:
#
# https://github.com/NixOS/nixpkgs/issues/321667
"LD=${stdenv.cc.bintools.bintools}/bin/${stdenv.cc.targetPrefix}ld"
]
++ (stdenv.hostPlatform.linux-kernel.makeFlags or [ ])
++ extraMakeFlags;
in
stdenv.mkDerivation (
builtins.foldl' lib.recursiveUpdate { } [
(drvAttrs config stdenv.hostPlatform.linux-kernel kernelPatches configfile)
{
inherit pname version;
enableParallelBuilding = true;
hardeningDisable = [
"bindnow"
"format"
"fortify"
"stackprotector"
"pic"
"pie"
];
makeFlags = [
"O=$(buildRoot)"
] ++ commonMakeFlags;
passthru = { inherit commonMakeFlags; };
karch = stdenv.hostPlatform.linuxArch;
}
(optionalAttrs (pos != null) { inherit pos; })
]
)
)

View file

@ -0,0 +1,70 @@
{
lib,
stdenv,
buildPackages,
fetchFromGitHub,
autoconf,
autoreconfHook,
zlib,
}:
stdenv.mkDerivation {
pname = "kexec-tools";
version = "main";
src = fetchFromGitHub {
owner = "horms";
repo = "kexec-tools";
rev = "v2.0.31";
hash = "sha256-Tgmc8mFlmzzRj7tEaBes7Udw4fRl6cSfe76iPNa3Ffs=";
};
dontPatchShebangs = true;
hardeningDisable = [
"format"
"pic"
"relro"
"pie"
];
preAutoreconf = "./bootstrap";
configurePlatforms = [
"build"
"host"
];
configureFlags = [ "BUILD_CC=${buildPackages.stdenv.cc.targetPrefix}cc" "--prefix=/"];
depsBuildBuild = [ buildPackages.stdenv.cc ];
installPhase = ''
make DESTDIR=$out install
'';
nativeBuildInputs = [
autoconf
autoreconfHook
];
buildInputs = [
zlib
];
enableParallelBuilding = true;
meta = with lib; {
homepage = "http://horms.net/projects/kexec/kexec-tools";
description = "Tools related to the kexec Linux feature";
platforms = platforms.linux;
badPlatforms = [
"microblaze-linux"
"microblazeel-linux"
"riscv64-linux"
"riscv32-linux"
"sparc-linux"
"sparc64-linux"
];
license = licenses.gpl2Only;
};
}

View file

@ -0,0 +1,41 @@
{
stdenv,
pkgs,
}:
stdenv.mkDerivation {
pname = pkgs.linux-firmware.name;
version = pkgs.linux-firmware.version;
src = pkgs.linux-firmware.src;
nativeBuildInputs = with pkgs; [
erofs-utils
cryptsetup
python3
rdfind
which
zstd
];
noBrokenSymlinks = true;
installTargets = [
"install-zst"
"dedup"
];
# inspo: https://gitlab.archlinux.org/archlinux/packaging/packages/linux-firmware/-/blob/main/PKGBUILD?ref_type=heads#L93
makeFlags = [
"DESTDIR=$(out)"
"ZSTD_CLEVEL=19"
"FIRMWAREDIR=/usr/lib/firmware"
];
preFixup = ''
# Remove broken symlinks if any, or just skip the check
find $out -xtype l -delete
'';
postInstall = ./post-install.sh;
}

View file

@ -0,0 +1,89 @@
set -ex -uo pipefail
_pick() {
local p="$1" f d; shift
for f; do
d="$out/$p/${f#$out/}"
mkdir -p "$(dirname "$d")"
mv "$f" "$(dirname "$d")"
rmdir -p --ignore-fail-on-non-empty "$(dirname "$f")"
done
}
_package() {
local p="$1"
mkdir -p $out/$p/usr/lib/extension-release.d
cat << EOF > $out/$p/usr/lib/extension-release.d/extension-release.$p
ID=patos
IMAGE_ID=$p
IMAGE_VERSION=$version
VERSION_ID=patos
EOF
mkfs.erofs --all-root -Efragments,dedupe,ztailpacking $out/$p.raw $out/$p
veritysetup format --root-hash-file $out/$p.roothash $out/$p.raw $out/$p.verity
rm -rf $out/$p
}
# split into systemd sysext packages
fwdir=$out/usr/lib/firmware
# we don't care about amd-ucode (we use nixpkg amd-ucode instead)
_pick amd-ucode "${fwdir}"/amd-ucode
rm -rf $out/amd-ucode
_pick linux-firmware-amdgpu "${fwdir}"/amdgpu
_package linux-firmware-amdgpu
_pick linux-firmware-atheros "${fwdir}"/{ar[0-9]*,ath*,carl9170*,htc_*,qca,wil6210*}
_package linux-firmware-atheros
_pick linux-firmware-broadcom "${fwdir}"/{bnx2*,brcm,cypress,tigon}
_package linux-firmware-broadcom
_pick linux-firmware-cirrus "${fwdir}"/{cirrus,cs42l43*}
_package linux-firmware-cirrus
_pick linux-firmware-intel "${fwdir}"/{e100,hfi1_*,i915,intel,isci,iwlwifi*,ixp4xx,qat_*,xe}
_package linux-firmware-intel
_pick linux-firmware-liquidio "${fwdir}"/liquidio
_package linux-firmware-liquidio
_pick linux-firmware-marvell "${fwdir}"/{libertas,mwl8k,mwlwifi,mrvl}
_package linux-firmware-marvell
_pick linux-firmware-mediatek "${fwdir}"/{mediatek,mt7*,vpu_*,rt[237]*}
_package linux-firmware-mediatek
_pick linux-firmware-mellanox "${fwdir}"/mellanox
_package linux-firmware-mellanox
_pick linux-firmware-nfp "${fwdir}"/netronome
_package linux-firmware-nfp
_pick linux-firmware-nvidia "${fwdir}"/nvidia
_package linux-firmware-nvidia
_pick linux-firmware-qcom "${fwdir}"/{qcom,a300_*}
_package linux-firmware-qcom
_pick linux-firmware-qlogic "${fwdir}"/{qlogic,qed,ql2???_*,c{b,t,t2}fw-*}
_package linux-firmware-qlogic
_pick linux-firmware-radeon "${fwdir}"/radeon
_package linux-firmware-radeon
_pick linux-firmware-realtek "${fwdir}"/{realtek,rtlwifi,rtw8*,rtl_*}
_package linux-firmware-realtek
# The rest will be packaged as 'other'
_pick linux-firmware-other "${fwdir}"
_package linux-firmware-other
#clean up
rm -rf $out/usr
pushd $out
sha256sum * > SHA256SUMS
popd

61
pkgs/lvm2/default.nix Normal file
View file

@ -0,0 +1,61 @@
{
stdenv,
pkgs,
fetchurl,
lib,
pkg-config,
libaio,
udev,
}:
stdenv.mkDerivation {
pname = "lvm2";
version = pkgs.lvm2.version;
src = pkgs.lvm2.src;
nativeBuildInputs = [
pkg-config
];
buildInputs = [
libaio
udev
];
configureFlags = [
"--prefix=/"
"--sbindir=/usr/bin"
"--sysconfdir=/etc"
"--localstatedir=/var"
"--enable-cmdlib"
"--enable-dmeventd"
"--enable-lvmpolld"
"--enable-pkgconfig"
"--enable-udev_rules"
"--enable-udev_sync"
"--enable-write_install"
"--with-cache=internal"
"--with-thin=internal"
];
preInstall = ''
mkdir -p $out
export DESTDIR=$out
'';
doCheck = false;
meta = with lib; {
homepage = "http://sourceware.org/lvm2/";
description = "Tools to support Logical Volume Management (LVM) on Linux";
platforms = platforms.linux;
license = with licenses; [
gpl2Only
bsd2
lgpl21
];
maintainers = with maintainers; [
raskin
ajs124
];
};
}

164
pkgs/openssl/default.nix Normal file
View file

@ -0,0 +1,164 @@
{
lib,
pkgs,
stdenv,
fetchurl,
perl,
makeBinaryWrapper,
withCryptodev ? false,
cryptodev,
withZlib ? false,
zlib,
enableSSL2 ? false,
enableSSL3 ? false,
enableMD2 ? false,
enableKTLS ? stdenv.hostPlatform.isLinux,
static ? stdenv.hostPlatform.isStatic,
removeReferencesTo,
}:
stdenv.mkDerivation rec {
pname = "openssl";
version = pkgs.openssl.version;
src = pkgs.openssl.src;
outputs = [ "out" ];
nativeBuildInputs =
lib.optional (!stdenv.hostPlatform.isWindows) makeBinaryWrapper
++ [ perl ]
++ lib.optionals static [ removeReferencesTo ];
buildInputs = lib.optional withCryptodev cryptodev ++ lib.optional withZlib zlib;
# TODO(@Ericson2314): Improve with mass rebuild
configurePlatforms = [ ];
configureScript =
{
armv5tel-linux = "./Configure linux-armv4 -march=armv5te";
armv6l-linux = "./Configure linux-armv4 -march=armv6";
armv7l-linux = "./Configure linux-armv4 -march=armv7-a";
x86_64-darwin = "./Configure darwin64-x86_64-cc";
aarch64-darwin = "./Configure darwin64-arm64-cc";
x86_64-linux = "./Configure linux-x86_64";
x86_64-solaris = "./Configure solaris64-x86_64-gcc";
powerpc64-linux = "./Configure linux-ppc64";
riscv32-linux = "./Configure ${
if lib.versionAtLeast version "3.2" then "linux32-riscv32" else "linux-latomic"
}";
riscv64-linux = "./Configure linux64-riscv64";
}
.${stdenv.hostPlatform.system} or (
if stdenv.hostPlatform == stdenv.buildPlatform then
"./config"
else if stdenv.hostPlatform.isBSD then
if stdenv.hostPlatform.isx86_64 then
"./Configure BSD-x86_64"
else if stdenv.hostPlatform.isx86_32 then
"./Configure BSD-x86" + lib.optionalString stdenv.hostPlatform.isElf "-elf"
else
"./Configure BSD-generic${toString stdenv.hostPlatform.parsed.cpu.bits}"
else if stdenv.hostPlatform.isMinGW then
"./Configure mingw${
lib.optionalString (stdenv.hostPlatform.parsed.cpu.bits != 32) (
toString stdenv.hostPlatform.parsed.cpu.bits
)
}"
else if stdenv.hostPlatform.isLinux then
if stdenv.hostPlatform.isx86_64 then
"./Configure linux-x86_64"
else if stdenv.hostPlatform.isMicroBlaze then
"./Configure linux-latomic"
else if stdenv.hostPlatform.isMips32 then
"./Configure linux-mips32"
else if stdenv.hostPlatform.isMips64n32 then
"./Configure linux-mips64"
else if stdenv.hostPlatform.isMips64n64 then
"./Configure linux64-mips64"
else
"./Configure linux-generic${toString stdenv.hostPlatform.parsed.cpu.bits}"
else if stdenv.hostPlatform.isiOS then
"./Configure ios${toString stdenv.hostPlatform.parsed.cpu.bits}-cross"
else
throw "Not sure what configuration to use for ${stdenv.hostPlatform.config}"
);
# OpenSSL doesn't like the `--enable-static` / `--disable-shared` flags.
dontAddStaticConfigureFlags = true;
configureFlags =
[
"shared" # "shared" builds both shared and static libraries
"--prefix=/"
"--libdir=lib"
"--openssldir=/etc/ssl"
]
++ lib.optionals withCryptodev [
"-DHAVE_CRYPTODEV"
"-DUSE_CRYPTODEV_DIGESTS"
]
++ lib.optional enableMD2 "enable-md2"
++ lib.optional enableSSL2 "enable-ssl2"
++ lib.optional enableSSL3 "enable-ssl3"
# We select KTLS here instead of the configure-time detection (which we patch out).
# KTLS should work on FreeBSD 13+ as well, so we could enable it if someone tests it.
++ lib.optional (lib.versionAtLeast version "3.0.0" && enableKTLS) "enable-ktls"
++ lib.optional (lib.versionAtLeast version "1.1.1" && stdenv.hostPlatform.isAarch64) "no-afalgeng"
# OpenSSL needs a specific `no-shared` configure flag.
# See https://wiki.openssl.org/index.php/Compilation_and_Installation#Configure_Options
# for a comprehensive list of configuration options.
++ lib.optional (lib.versionAtLeast version "1.1.1" && static) "no-shared"
++ lib.optional (lib.versionAtLeast version "3.0.0" && static) "no-module"
# This introduces a reference to the CTLOG_FILE which is undesired when
# trying to build binaries statically.
++ lib.optional static "no-ct"
++ lib.optional withZlib "zlib"
# /dev/crypto support has been dropped in OpenBSD 5.7.
#
# OpenBSD's ports does this too,
# https://github.com/openbsd/ports/blob/a1147500c76970fea22947648fb92a093a529d7c/security/openssl/3.3/Makefile#L25.
#
# https://github.com/openssl/openssl/pull/10565 indicated the
# intent was that this would be configured properly automatically,
# but that doesn't appear to be the case.
++ lib.optional stdenv.hostPlatform.isOpenBSD "no-devcryptoeng"
++ lib.optionals (stdenv.hostPlatform.isMips && stdenv.hostPlatform ? gcc.arch) [
# This is necessary in order to avoid openssl adding -march
# flags which ultimately conflict with those added by
# cc-wrapper. Openssl assumes that it can scan CFLAGS to
# detect any -march flags, using this perl code:
#
# && !grep { $_ =~ /-m(ips|arch=)/ } (@{$config{CFLAGS}})
#
# The following bogus CFLAGS environment variable triggers the
# the code above, inhibiting `./Configure` from adding the
# conflicting flags.
"CFLAGS=-march=${stdenv.hostPlatform.gcc.arch}"
];
postPatch = ''
patchShebangs Configure
'';
installPhase = ''
make DESTDIR=$out install
rm -rf $out/etc/ssl/*.dist $out/etc/ssl/misc
'';
enableParallelBuilding = true;
meta = {
homepage = "https://www.openssl.org/";
changelog = "https://github.com/openssl/openssl/blob/openssl-${version}/CHANGES.md";
description = "Cryptographic library that implements the SSL and TLS protocols";
license = lib.licenses.openssl;
mainProgram = "openssl";
maintainers = with lib.maintainers; [ thillux ] ++ lib.teams.stridtech.members;
pkgConfigModules = [
"libcrypto"
"libssl"
"openssl"
];
platforms = lib.platforms.all;
};
}

92
pkgs/rootfs/mkinitrd.nix Normal file
View file

@ -0,0 +1,92 @@
{
pkgs,
runCommand,
...
}:
let
secureBootEnroll = ./secure-boot-enroll.sh;
in
runCommand "patos-initrd" {
inherit secureBootEnroll;
nativeBuildInputs = with pkgs; [
cpio
xz
];
}
''
echo "Building initram disk"
mkdir -p $out/root
pushd $out/root
### copy rootfs
cp -prP ${pkgs.patos.rootfs}/* .
find . -type d -exec chmod 755 {} \;
mkdir sysroot
### create directories
ln -sf ../usr/lib/systemd/systemd init
### Create needed files
echo patos > ./etc/hostname
ln -sf /etc/os-release ./etc/initrd-release
# set default target to initrd inside initrd
ln -sf initrd.target ./usr/lib/systemd/system/default.target
# setup secure boot
cat $secureBootEnroll > ./usr/bin/secure-boot-enroll
chmod +x ./usr/bin/secure-boot-enroll
cat <<EOF > ./usr/lib/systemd/system/secure-boot-enroll.service
[Unit]
Description=Enroll Secure Boot
DefaultDependencies=false
After=sysroot-run.mount
Requires=sysroot-run.mount
Before=systemd-repart.service initrd.target shutdown.target sysinit.target
ConditionKernelCommandLine=patos.secureboot=true
ConditionPathExists=|!/sys/firmware/efi/efivars/PK-8be4df61-93ca-11d2-aa0d-00e098032b8c
[Service]
Type=oneshot
ExecStart=/usr/bin/secure-boot-enroll
RemainAfterExit=yes
EOF
ln -sf ../secure-boot-enroll.service ./usr/lib/systemd/system/initrd-root-fs.target.wants/secure-boot-enroll.service
# bind mount /run to /sysroot/run
cat <<EOF > ./usr/lib/systemd/system/sysroot-run.mount
[Unit]
Before=initrd-fs.target
DefaultDependencies=false
[Mount]
Options=bind
What=/run
Where=/sysroot/run
EOF
mkdir ./usr/lib/systemd/system/initrd-fs.target.requires/
ln -sf ../sysroot-run.mount ./usr/lib/systemd/system/initrd-fs.target.requires/sysroot-run.mount
# repart: generate crypttab and fstab under /run
mkdir ./usr/lib/systemd/system/systemd-repart.service.d
cat <<EOF > ./usr/lib/systemd/system/systemd-repart.service.d/override.conf
[Unit]
After=sysroot-run.mount
Requires=sysroot-run.mount
[Service]
Environment=SYSTEMD_REPART_MKFS_OPTIONS_BTRFS=--nodiscard
ExecStart=
ExecStart=systemd-repart --dry-run=no --generate-crypttab=/run/crypttab --generate-fstab=/run/fstab
EOF
ln -sf ../systemd-repart.service ./usr/lib/systemd/system/initrd-root-fs.target.wants/systemd-repart.service
# gen initrd
find . -print0 | cpio --null --owner=root:root -o --format=newc | xz -9 --check=crc32 > ../initrd.xz
popd
rm -rf $out/root
''

249
pkgs/rootfs/mkrootfs.nix Normal file
View file

@ -0,0 +1,249 @@
{
pkgs,
version,
revision,
runCommand,
}:
let
defaultPassword = "patos";
in
runCommand "patos-rootfs"
{
inherit version;
nativeBuildInputs = with pkgs; [
stdenv.cc
patchelf
glibc
binutils
];
}
''
### create directory structure
mkdir -p $out/etc/repart.d $out/dev $out/proc $out/sys \
$out/tmp $out/root $out/run $out/boot $out/mnt $out/home $out/srv $out/var
ln -sf /usr/bin $out/bin
ln -sf /usr/bin $out/sbin
ln -sf /usr/lib $out/lib
ln -sf /usr/lib $out/lib64
ln -sf /tmp $out/var/tmp
ln -sf ../proc/self/mounts $out/etc/mtab
### install systemd
cp -Pr ${pkgs.patos.systemd}/* $out/
find $out -type d -exec chmod 755 {} \;
rm -rf $out/usr/include
rm -rf $out/usr/sbin
ln -sf /usr/bin $out/usr/sbin
# enable in ramdisk instead
rm -f $out/usr/lib/systemd/system/sysinit.target.wants/systemd-repart.service
rm -f $out/usr/lib/systemd/system/initrd-root-fs.target.wants/systemd-repart.service
rm -f $out/usr/lib/systemd/ukify
rm -f $out/usr/bin/ukify
rm -f $out/usr/lib/udev/rules.d/90-vconsole.rules
ln -s /run/systemd/resolve/stub-resolv.conf $out/etc/resolv.conf
cat <<EOF > $out/etc/os-release
NAME=PatOS
PRETTY_NAME=PatOS v${version} (Pre-Alpha)
IMAGE_ID=patos
ID=patos
IMAGE_VERSION=${version}
VERSION=${version}
VERSION_ID=patos
BUILD_ID=${revision}
EOF
cat <<EOF > $out/etc/issue
<<< Welcome to PatOS v${version}-${revision} (Pre-Alpha) (\m) - \l >>>
EOF
# replace agetty with busybox getty (optionally autologin)
mkdir $out/usr/lib/systemd/system/serial-getty@.service.d
cat <<EOF > $out/usr/lib/systemd/system/serial-getty@.service.d/override.conf
[Service]
ExecStart=
ExecStart=-/bin/login -f root
EOF
# ExecStart=-/sbin/getty -L %I 115200 vt100
# Configure systemd-repart
cat <<EOF > $out/etc/repart.d/10-esp.conf
[Partition]
Type=esp
Format=vfat
SizeMaxBytes=128M
SizeMinBytes=128M
EOF
cat <<EOF > $out/etc/repart.d/20-root-a.conf
[Partition]
Type=root
SizeMaxBytes=64M
SizeMinBytes=64M
EOF
cat <<EOF > $out/etc/repart.d/22-root-verify-a.conf
[Partition]
Type=root-verity
EOF
cat <<EOF > $out/etc/repart.d/30-root-b.conf
[Partition]
Type=root
Label=_empty
SizeMaxBytes=64M
SizeMinBytes=64M
ReadOnly=1
EOF
cat <<EOF > $out/etc/repart.d/32-root-verity-b.conf
[Partition]
Type=root-verity
Label=_empty
ReadOnly=1
EOF
cat <<EOF > $out/etc/repart.d/40-var.conf
[Partition]
Type=var
Format=btrfs
MakeDirectories=/var/lib/confexts /var/lib/extensions /var/lib/portables /var/lib/extensions.d /var/.snapshots
MountPoint=/var
Label=patos-state
Encrypt=tpm2
EncryptedVolume=patos-state:none:tpm2-device=auto,luks,discard
Subvolumes=/var/lib/confexts /var/lib/extensions /var/lib/portables /var/lib/extensions.d /var/.snapshots
MountPoint=/var/lib/confexts:subvol=/var/lib/confexts
MountPoint=/var/lib/extensions:subvol=/var/lib/extensions
MountPoint=/var/lib/portables:subvol=/var/lib/portables
MountPoint=/var/lib/extensions.d:subvol=/var/lib/extensions.d
MountPoint=/var/.snapshots:subvol=/var/.snapshots
SizeMinBytes=1G
Minimize=off
FactoryReset=yes
EOF
# as rootfs is read-only we need to configure the fstab and cryptsetup generators to look
# for config under /run (which are generated by systemd-repart in initrd)
rm -f $out/etc/systemd/system.conf
cat <<EOF > $out/etc/systemd/system.conf
[Manager]
DefaultEnvironment=PATH=/bin:/sbin:/usr/bin
ManagerEnvironment=PATH=/bin:/sbin:/usr/bin SYSTEMD_CRYPTTAB=/run/crypttab SYSTEMD_SYSROOT_FSTAB=/run/fstab SYSTEMD_FSTAB=/run/fstab
EOF
### create /etc/profile
cat <<EOF > $out/etc/profile
export PATH=/usr/bin
export TERMINFO=/usr/share/terminfo
export PS1='\u@\h:\w\$ '
EOF
### install PatOS glibc
cp -P ${pkgs.patos.glibc}/lib/*.so* $out/usr/lib/
### install openssl
cp -P ${pkgs.patos.openssl}/lib/*.so* $out/usr/lib/
cp -Pr ${pkgs.patos.openssl}/etc/ssl $out/etc/
### install busybox
cp ${pkgs.patos.busybox}/bin/busybox $out/usr/bin/
$out/usr/bin/busybox --list | xargs -I {} ln -sf busybox $out/usr/bin/{}
### install dbus broker
cp -r ${pkgs.patos.dbus-broker}/* $out/
### install kexec
cp -Pr ${pkgs.patos.kexec}/sbin/kexec $out/usr/bin/
### install dmsetup udev rules
cp -P ${pkgs.patos.lvm2}/usr/bin/dmsetup $out/usr/bin/
cp -P ${pkgs.patos.lvm2}/lib/libdevmapper.so* $out/usr/lib/
cp -P ${pkgs.patos.lvm2}/lib/udev/rules.d/* $out/usr/lib/udev/rules.d/
### install btrfs progs
cp -Pr ${pkgs.btrfs-progs}/bin/* $out/usr/bin/
cp -Pr ${pkgs.btrfs-progs}/lib/* $out/usr/lib/
sed -i '1s|^#!.*|#!/bin/sh|' $out/usr/bin/fsck.btrfs
### install fsck tools
rm -f $out/usr/bin/fsck
cp -P ${pkgs.util-linuxMinimal}/bin/fsck $out/usr/bin/
cp -Pr ${pkgs.dosfstools}/bin/fsck* $out/usr/bin/
### install tpm2 libs
cp -P ${pkgs.patos.tpm2-tss}/lib/*.so* $out/usr/lib/
### install lib kmod
cp -P ${pkgs.kmod.lib}/lib/*.so* $out/usr/lib/
cp -P ${pkgs.kmod}/bin/* $out/usr/bin
### install libbpf
cp -P ${pkgs.libbpf}/lib/libbpf*.so* $out/usr/lib/
### install secure boot tools
cp -P ${pkgs.sbctl}/bin/sbctl $out/usr/bin/
rm -f $out/usr/bin/tar
rm -f $out/usr/bin/blkid
cp -P ${pkgs.gnutar}/bin/tar $out/usr/bin/
cp -P ${pkgs.util-linuxMinimal}/bin/blkid $out/usr/bin/
cp -P ${pkgs.util-linuxMinimal}/bin/lsblk $out/usr/bin/
### install xq (jq clone)
cp -P ${pkgs.xq}/bin/xq $out/usr/bin/
ln -sf /usr/bin/xq $out/usr/bin/jq
### install ca cert bundle
chmod 755 $out/etc/ssl $out/etc/ssl/certs
cp -P ${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt $out/etc/ssl/cert.pem
ln -sf ../cert.pem $out/etc/ssl/certs/ca-certificates.crt
ln -sf ../cert.pem $out/etc/ssl/certs/ca-bundle.crt
# no need for pkgconfig, removing..
rm -rf $out/usr/lib/pkgconfig
# setup default files
${pkgs.patos.systemd}/usr/bin/systemd-hwdb --root=$out --usr update
${pkgs.patos.systemd}/usr/bin/systemd-tmpfiles --root=$out $out/usr/lib/tmpfiles.d/etc.conf --create
cp $out/usr/share/factory/etc/nsswitch.conf $out/etc/
cp $out/usr/share/factory/etc/locale.conf $out/etc/
cp $out/usr/share/factory/etc/vconsole.conf $out/etc/
# install sys users
mkdir creds
echo -n ${defaultPassword} > creds/passwd.plaintext-password.root
CREDENTIALS_DIRECTORY=$PWD/creds SYSTEMD_CRYPT_PREFIX='$6$' ${pkgs.patos.systemd}/usr/bin/systemd-sysusers --root=$out rootfs/usr/lib/sysusers.d/*.conf
chmod 600 $out/etc/shadow
rm -rf creds
# Ephemeral machine-id until registration
# ln -sf /run/machine-id $out/etc/machine-id
# FIXME: above line does not work in systemd > 257
${pkgs.patos.systemd}/usr/bin/systemd-machine-id-setup --root=$out
### Find and install all shared libs
find $out -type f -executable -exec ldd {} \; | awk '{print $3}' | \
grep -vE "(systemd|glibc|openssl|tpm2|devmapper)" | \
sort -u | xargs -I {} cp {} $out/usr/lib/
find $out -type f -executable -exec chmod 755 {} \;
# patch ELFs
interpreter=$(patchelf --print-interpreter $out/usr/bin/busybox)
ldLinux=$(basename $interpreter)
find $out -type f -executable -exec patchelf --set-rpath /lib:/usr/lib:/usr/lib/systemd:/usr/lib/cryptsetup {} \;
find $out -type f -executable -exec patchelf --set-interpreter /lib/$ldLinux {} \;
patchelf --remove-rpath $out/usr/lib/$ldLinux
# strip binaries
find $out -type f -executable -exec $STRIP {} \;
find $out -type d -exec chmod 755 {} \;
# install kernel modules
cp -r ${pkgs.patos.kernel}/lib/modules $out/usr/lib/
find $out/usr/lib/modules -type d -exec chmod 755 {} \;
''

View file

@ -0,0 +1,23 @@
#!/bin/sh
set -ex -uo pipefail
SETUP_MODE=$(sbctl status --json | jq -r '.setup_mode')
[ "$SETUP_MODE" = "false" ] && exit 0
cat <<EOL> /run/sbctl.yml
---
keydir: /sysroot/boot/sbctl/keys
guid: /sysroot/boot/sbctl/GUID
EOL
ESP=$(blkid --label ESP)
mount $ESP /sysroot/boot && \
sbctl --config /run/sbctl.yml create-keys && \
sbctl --config /run/sbctl.yml enroll-keys --yolo && \
# Sign EFIs
find /sysroot/boot -type f \( -iname "*.efi" -o -iname "*.EFI" \) -print0 | xargs -I {} sbctl --config /run/sbctl.yml sign {}
umount /sysroot/boot && \
systemctl reboot -f

View file

@ -0,0 +1,55 @@
{
pkgs,
version,
arch,
stdenv,
updateUrl,
...
}:
let
cpu_arch = arch.${stdenv.hostPlatform.system};
in
pkgs.callPackage ../../lib/make-sysext.nix {
name = "patos-containerd";
version = version;
arch = cpu_arch;
updateUrl = updateUrl;
packages = [
{ drv = pkgs.containerd; path = "bin/"; }
{ drv = pkgs.runc; path = "bin/.runc-wrapped"; destpath="bin/runc"; }
{ drv = pkgs.writeText "config.toml" ''
version = 3
# set containerd's OOM score
oom_score = -999
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc.options]
SystemdCgroup = true
'';
path = "share/containerd/config.toml";
}
];
services = [
{
unit = "containerd.service";
content = ''
[Unit]
Description=Containerd Container Runtime
After=network.target
[Service]
Delegate=yes
Environment=CONTAINERD_CONFIG=/usr/share/containerd/config.toml
ExecStart=/usr/bin/containerd --config ''${CONTAINERD_CONFIG}
KillMode=process
Restart=always
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
[Install]
WantedBy=multi-user.target
'';
}
];
}

120
pkgs/sysext/debug-tools.nix Normal file
View file

@ -0,0 +1,120 @@
{
pkgs,
stdenv,
version,
arch,
updateUrl,
...
}:
let
cpu_arch = arch.${stdenv.hostPlatform.system};
in
pkgs.callPackage ../../lib/make-sysext.nix {
name = "patos-debug-tools";
version = version;
arch = cpu_arch;
updateUrl = updateUrl;
packages = [
{ drv = pkgs.curl; path = "bin/"; }
{ drv = pkgs.bash; path = "bin/"; }
{ drv = pkgs.keyutils; path = "bin/"; }
{ drv = pkgs.gnutar; path = "bin/"; }
{ drv = pkgs.strace; path = "bin/"; }
{ drv = pkgs.cryptsetup; path = "bin/"; }
{ drv = pkgs.erofs-utils; path = "bin/"; }
{ drv = pkgs.openssh; path = "libexec/sftp-server"; destpath="lib/ssh/sftp-server"; }
{ drv = pkgs.dropbear.override { sftpPath = "/usr/lib/ssh/sftp-server";}; path = "bin/"; }
{ drv = pkgs.ldns; path = "bin/"; }
{ drv = pkgs.ldns; path = "lib/"; }
{ drv = pkgs.binutils-unwrapped; path = "bin/"; }
{ drv = pkgs.binutils-unwrapped.lib; path = "lib/"; }
{ drv = pkgs.util-linuxMinimal; path = "bin/"; }
{ drv = pkgs.util-linuxMinimal.mount; path = "bin/"; }
{ drv = pkgs.util-linuxMinimal.login; path = "bin/"; }
{ drv = pkgs.util-linuxMinimal.swap; path = "bin/"; }
{ drv = pkgs.procps; path = "bin/"; }
{ drv = pkgs.procps; path = "lib/"; }
{ drv = pkgs.patos.glibc; path = "bin/ldd"; }
{ drv = pkgs.patos.tpm2-tools; path = "bin/tpm2"; }
{ drv = pkgs.patos.openssl; path = "bin/openssl"; }
# shared lib required for mkfs.erofs
{ drv = pkgs.lz4.lib; path = "lib/"; }
{ drv = pkgs.xxHash; path = "lib/"; }
{ drv = pkgs.libdeflate; path = "lib/"; }
# shared lib required for cryptsetup
{ drv = pkgs.popt; path = "lib/"; }
# shared lib required for strace
{ drv = pkgs.elfutils.out; path = "lib/"; }
# shared lib required for bash
{ drv = pkgs.readline.out; path = "lib/"; }
{ drv = pkgs.ncurses.out; path = "lib/"; }
{ drv = pkgs.ncurses.out; path = "share/terminfo/"; }
# override prefix for file command
{ drv = pkgs.file.overrideAttrs (oldAttrs: {
configureFlags = [ "--prefix=/usr" ];
outputs = [ "out" ];
makeFlags = oldAttrs.makeFlags or [] ++ [ "DESTDIR=$(out)" ];
});
path = "usr/";
destpath="/";
}
];
services = [
{
unit = "dropbear.socket";
content = ''
[Unit]
Conflicts=dropbear.service
[Socket]
ListenStream=22
Accept=yes
[Install]
WantedBy=sockets.target
Also=dropbearkey.service
'';
}
{
unit = "dropbear@.service";
content = ''
[Unit]
Description=SSH Per-Connection Server
Wants=dropbearkey.service
After=network.target dropbearkey.service
[Service]
Environment="DROPBEAR_RSAKEY_DIR=/var/lib/dropbear"
ExecStart=-/usr/bin/dropbear -i -r ''${DROPBEAR_RSAKEY_DIR}/dropbear_rsa_host_key
ExecReload=/usr/bin/kill -HUP $MAINPID
StandardInput=socket
KillMode=process
'';
}
{
unit = "dropbearkey.service";
content = ''
[Unit]
Description=SSH Key Generation
RequiresMountsFor=/var /var/lib
ConditionPathExists=!/var/lib/dropbear/dropbear_rsa_host_key
[Service]
Type=oneshot
Environment="DROPBEAR_RSAKEY_DIR=/var/lib/dropbear"
Environment="DROPBEAR_RSAKEY_ARGS=-s 2048"
ExecStart=/usr/bin/mkdir -p ''${DROPBEAR_RSAKEY_DIR}
ExecStart=/usr/bin/dropbearkey -t rsa -f ''${DROPBEAR_RSAKEY_DIR}/dropbear_rsa_host_key ''${DROPBEAR_RSAKEY_ARGS}
RemainAfterExit=yes
Nice=10
'';
}
];
}

View file

@ -0,0 +1,34 @@
{
pkgs,
version,
arch,
stdenv,
updateUrl,
...
}:
let
cpu_arch = arch.${stdenv.hostPlatform.system};
in
pkgs.callPackage ../../lib/make-sysext.nix {
name = "patos-firewall-tools";
version = version;
arch = cpu_arch;
updateUrl = updateUrl;
packages = [
# network/firewalling
{ drv = pkgs.iproute2; path = "bin/"; }
{ drv = pkgs.nftables; path = "bin/"; }
{ drv = pkgs.wireguard-tools; path = "bin/.wg-wrapped"; destpath = "bin/wg"; }
# deps
{ drv = pkgs.nftables; path = "lib/"; }
{ drv = pkgs.libnftnl; path = "lib/"; }
{ drv = pkgs.iptables; path = "lib/"; }
{ drv = pkgs.libgcc; path = "lib/"; }
{ drv = pkgs.libmnl; path = "lib/"; }
{ drv = pkgs.gmp; path = "lib/"; }
{ drv = pkgs.jansson.out; path = "lib/"; }
{ drv = pkgs.ncurses.out; path = "lib/"; }
{ drv = pkgs.libedit; path = "lib/"; }
];
}

View file

@ -7,7 +7,7 @@
...
}:
let
version = "257.3";
version = "devel";
# Use the command below to update `releaseTimestamp` on every (major) version
# change. More details in the commentary at mesonFlags.
@ -26,16 +26,18 @@ stdenv.mkDerivation (finalAttrs: {
src = fetchFromGitHub {
owner = "systemd";
repo = "systemd";
rev = "v${version}";
hash = "sha256-GvRn55grHWR6M+tA86RMzqinuXNpPZzRB4ApuGN/ZvU=";
rev = "2e5e17a5707ad6538d67e4d43088a6eb33f2d852"; # main
hash = "sha256-xPwGuS/vaA3/oe8szzI1bNadVHt623ZBz+HSj7x/4cM=";
};
dontCheckForBrokenSymlinks = true;
patches = [
./0017-meson.build-do-not-create-systemdstatedir.patch
./skip-verify-esp.patch
./enable-sysext-repart.patch
./sysupdate-fix.patch
];
dontCheckForBrokenSymlinks = true;
nativeBuildInputs = with pkgs; [
bash
pkg-config
@ -137,11 +139,12 @@ stdenv.mkDerivation (finalAttrs: {
postPatch =
''
substituteInPlace src/basic/path-util.h --replace "@defaultPathNormal@" "${placeholder "out"}/bin/"
''
+ ''
substituteInPlace meson.build \
--replace "find_program('clang'" "find_program('${stdenv.cc.targetPrefix}clang'"
'' +
''
substituteInPlace src/test/meson.build \
--replace "test_env.set('SYSTEMD_LANGUAGE_FALLBACK_MAP', language_fallback_map)" ""
''
+ ''
substituteInPlace src/ukify/ukify.py \
@ -150,7 +153,7 @@ stdenv.mkDerivation (finalAttrs: {
"'${targetPackages.stdenv.cc.bintools.targetPrefix}readelf'" \
--replace \
"/usr/lib/systemd/boot/efi" \
"$out/lib/systemd/boot/efi"
"$out/usr/lib/systemd/boot/efi"
''
# Finally, patch shebangs in scripts used at build time. This must not patch
# scripts that will end up in the output, to avoid build platform references
@ -171,7 +174,7 @@ stdenv.mkDerivation (finalAttrs: {
"--sysconfdir=/etc"
"--localstatedir=/var"
"--libdir=/usr/lib"
"--bindir=/bin"
"--bindir=/usr/bin"
"--includedir=/usr/include"
"--localedir=/usr/share/locale"
@ -190,7 +193,20 @@ stdenv.mkDerivation (finalAttrs: {
(lib.mesonOption "mode" "release")
(lib.mesonOption "tty-gid" "3") # tty in NixOS has gid 3
(lib.mesonOption "kmod-path" "/bin/kmod")
(lib.mesonOption "kmod-path" "/usr/bin/kmod")
(lib.mesonOption "kexec-path" "/usr/bin/kexec")
(lib.mesonOption "debug-shell" "/usr/bin/sh")
(lib.mesonOption "pamconfdir" "/etc/pam.d")
(lib.mesonOption "shellprofiledir" "/etc/profile.d")
(lib.mesonOption "dbuspolicydir" "/usr/share/dbus-1/system.d")
(lib.mesonOption "dbussessionservicedir" "/usr/share/dbus-1/services")
(lib.mesonOption "dbussystemservicedir" "/usr/share/dbus-1/system-services")
(lib.mesonOption "setfont-path" "/usr/bin/setfont")
(lib.mesonOption "loadkeys-path" "/usr/bin/loadkeys")
(lib.mesonOption "sulogin-path" "/usr/bin/sulogin")
(lib.mesonOption "nologin-path" "/usr/bin/nologin")
(lib.mesonOption "mount-path" "/usr/bin/mount")
(lib.mesonOption "umount-path" "/usr/bin/umount")
# SBAT
(lib.mesonOption "sbat-distro" "patos")
@ -300,7 +316,7 @@ stdenv.mkDerivation (finalAttrs: {
(lib.mesonBool "utmp" true)
(lib.mesonBool "log-trace" true)
(lib.mesonBool "kernel-install" true)
(lib.mesonBool "kernel-install" false)
(lib.mesonBool "quotacheck" false)
(lib.mesonBool "ldconfig" false)
(lib.mesonBool "install-sysconfdir" true)

View file

@ -0,0 +1,36 @@
diff --git a/src/repart/repart.c b/src/repart/repart.c
index 352384bfc0..e3e8bcae5f 100644
--- a/src/repart/repart.c
+++ b/src/repart/repart.c
@@ -9076,8 +9076,6 @@ static int parse_argv(int argc, char *argv[], X509 **ret_certificate, EVP_PKEY *
"Expected at most one argument, the path to the block device or image file.");
if (arg_make_ddi) {
- if (arg_definitions)
- return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Combination of --make-ddi= and --definitions= is not supported.");
if (!IN_SET(arg_empty, EMPTY_UNSET, EMPTY_CREATE))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Combination of --make-ddi= and --empty=%s is not supported.", empty_mode_to_string(arg_empty));
@@ -9744,21 +9742,7 @@ static int run(int argc, char *argv[]) {
if (r < 0)
return r;
- if (arg_make_ddi) {
- _cleanup_free_ char *d = NULL, *dp = NULL;
- assert(!arg_definitions);
-
- d = strjoin(arg_make_ddi, ".repart.d/");
- if (!d)
- return log_oom();
-
- r = search_and_access(d, F_OK, NULL, CONF_PATHS_STRV("systemd/repart/definitions"), &dp);
- if (r < 0)
- return log_error_errno(r, "DDI type '%s' is not defined: %m", arg_make_ddi);
-
- if (strv_consume(&arg_definitions, TAKE_PTR(dp)) < 0)
- return log_oom();
- } else
+ if (arg_make_ddi)
strv_uniq(arg_definitions);
r = context_read_definitions(context);

View file

@ -0,0 +1,24 @@
diff --git a/src/shared/find-esp.c b/src/shared/find-esp.c
index f830d6dfe3..7ad2a8cd1d 100644
--- a/src/shared/find-esp.c
+++ b/src/shared/find-esp.c
@@ -403,15 +403,15 @@ static int verify_esp(
"File system \"%s\" is not a FAT EFI System Partition (ESP) file system.", p);
}
- r = verify_fsroot_dir(pfd, p, flags, FLAGS_SET(flags, VERIFY_ESP_SKIP_DEVICE_CHECK) ? NULL : &devid);
- if (r < 0)
- return r;
-
/* In a container we don't have access to block devices, skip this part of the verification, we trust
* the container manager set everything up correctly on its own. */
if (FLAGS_SET(flags, VERIFY_ESP_SKIP_DEVICE_CHECK))
goto finish;
+ r = verify_fsroot_dir(pfd, p, flags, FLAGS_SET(flags, VERIFY_ESP_SKIP_DEVICE_CHECK) ? NULL : &devid);
+ if (r < 0)
+ return r;
+
if (devnum_is_zero(devid))
return log_full_errno(searching ? LOG_DEBUG : LOG_ERR,
SYNTHETIC_ERRNO(searching ? EADDRNOTAVAIL : ENODEV),

View file

@ -0,0 +1,13 @@
diff --git a/src/sysupdate/sysupdate-transfer.c b/src/sysupdate/sysupdate-transfer.c
index d3e71bb21e..ba3747dead 100644
--- a/src/sysupdate/sysupdate-transfer.c
+++ b/src/sysupdate/sysupdate-transfer.c
@@ -684,7 +684,7 @@ int transfer_resolve_paths(
return r;
r = resource_resolve_path(&t->target, root, /*relative_to_directory=*/ NULL, node);
- if (r < 0)
+ if (r < 0 && !RESOURCE_IS_FILESYSTEM((&t->target)->type))
return r;
return 0;

View file

@ -0,0 +1,46 @@
{
stdenv,
pkgs,
fetchurl,
lib,
pandoc,
pkg-config,
curl,
openssl,
libuuid,
}:
stdenv.mkDerivation {
pname = "tpm2-tools";
version = pkgs.tpm2-tools.version;
src = pkgs.tpm2-tools.src;
nativeBuildInputs = [
pandoc
pkg-config
];
buildInputs = [
curl
openssl
pkgs.patos.tpm2-tss
libuuid
];
# Unit tests disabled, as they rely on a dbus session
configureFlags = [ "--prefix=/" ];
preInstall = ''
mkdir -p $out
export DESTDIR=$out
'';
doCheck = false;
meta = with lib; {
description = "Command line tools that provide access to a TPM 2.0 compatible device";
homepage = "https://github.com/tpm2-software/tpm2-tools";
license = licenses.bsd3;
platforms = platforms.linux;
maintainers = with maintainers; [ tomfitzhenry ];
};
}

82
pkgs/tpm2-tss/default.nix Normal file
View file

@ -0,0 +1,82 @@
{
stdenv,
pkgs,
lib,
fetchFromGitHub,
autoreconfHook,
autoconf-archive,
pkg-config,
doxygen,
perl,
openssl,
json_c,
curl,
libgcrypt,
uthash,
git,
libuuid,
libtpms,
}:
stdenv.mkDerivation rec {
pname = "tpm2-tss";
version = pkgs.tpm2-tss.version;
src = pkgs.tpm2-tss.src;
patches = [
./no-shadow.patch
];
postPatch = ''
substituteInPlace ./bootstrap \
--replace-fail 'git describe --tags --always --dirty' 'echo "${version}"'
'';
outputs = [
"out"
];
nativeBuildInputs = [
autoreconfHook
autoconf-archive
pkg-config
doxygen
perl
git
];
buildInputs = [
openssl
json_c
curl
libgcrypt
uthash
libuuid
libtpms
];
strictDeps = true;
preAutoreconf = "./bootstrap";
enableParallelBuilding = true;
configureFlags = [
"--prefix=/"
];
preInstall = ''
mkdir -p $out
export DESTDIR=$out
'';
doCheck = false;
meta = with lib; {
description = "OSS implementation of the TCG TPM2 Software Stack (TSS2)";
homepage = "https://github.com/tpm2-software/tpm2-tss";
license = licenses.bsd2;
platforms = platforms.unix;
maintainers = with maintainers; [ baloo ];
};
}

View file

@ -0,0 +1,16 @@
diff --git a/configure.ac b/configure.ac
index e2d579b8..0eac4ff3 100644
--- a/configure.ac
+++ b/configure.ac
@@ -672,9 +672,9 @@ AS_IF([test "$HOSTOS" = "Linux" && test "x$systemd_sysusers" != "xyes"],
AC_CHECK_PROG(adduser, adduser, yes)
AC_CHECK_PROG(addgroup, addgroup, yes)
AS_IF([test "x$addgroup" != "xyes" && test "x$groupadd" != "xyes" ],
- [AC_MSG_ERROR([addgroup or groupadd are needed.])])
+ [AC_MSG_WARN([addgroup or groupadd are needed.])])
AS_IF([test "x$adduser" != "xyes" && test "x$useradd" != "xyes" ],
- [AC_MSG_ERROR([adduser or useradd are needed.])])])
+ [AC_MSG_WARN([adduser or useradd are needed.])])])
AC_SUBST([PATH])

View file

@ -1,21 +0,0 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: nikstur <nikstur@outlook.com>
Date: Mon, 6 Nov 2023 22:51:38 +0100
Subject: [PATCH] meson.build: do not create systemdstatedir
---
meson.build | 1 -
1 file changed, 1 deletion(-)
diff --git a/meson.build b/meson.build
index bffda86845..cb5dcec0f9 100644
--- a/meson.build
+++ b/meson.build
@@ -2781,7 +2781,6 @@ install_data('LICENSE.GPL2',
install_subdir('LICENSES',
install_dir : docdir)
-install_emptydir(systemdstatedir)
#####################################################################

View file

@ -0,0 +1,52 @@
{
pkgs,
...
}:
pkgs.writeShellApplication {
name = "qemu-aarch64-uefi-tpm";
runtimeInputs = with pkgs; [
qemu
swtpm
];
text =
''
set -ex
state="/tmp/patos-qemu-$USER"
rm -rf "$state"
mkdir -m 700 "$state"
qemu-img create -f qcow2 -F raw -b "$(readlink -e "$1")" "$state/disk.qcow2" 2G
OVMF_FD=$(nix-build '<nixpkgs>' --no-out-link -A OVMF.fd --system aarch64-linux)
cp "$OVMF_FD/AAVMF/vars-template-pflash.raw" "$state/vars-pflash.raw"
chmod u+w "$state/vars-pflash.raw"
swtpm socket -d --tpmstate dir="$state" \
--ctrl type=unixio,path="$state/swtpm-sock" \
--tpm2 \
--log file="$state/swtpm.log",level=20
qemu-system-aarch64 \
-machine virt,gic-version=max \
-cpu max \
-smp 8 \
-m 4G \
-display none \
-chardev "stdio,id=char0,mux=on,logfile=$state/console.log,signal=off" \
-serial chardev:char0 \
-mon chardev=char0 \
-chardev socket,id=chrtpm,path="$state/swtpm-sock" \
-tpmdev emulator,id=tpm0,chardev=chrtpm \
-device tpm-tis-device,tpmdev=tpm0 \
-drive "if=pflash,format=raw,unit=0,readonly=on,file=$OVMF_FD/AAVMF/QEMU_EFI-pflash.raw" \
-drive "if=pflash,format=raw,unit=1,file=$state/vars-pflash.raw" \
-device virtio-gpu-pci \
-device virtio-net-pci,netdev=wan \
-netdev user,id=wan \
-device virtio-rng-pci,rng=rng0 \
-object rng-random,filename=/dev/urandom,id=rng0 \
-device virtio-serial-pci \
-drive "format=qcow2,if=virtio,file=$state/disk.qcow2"
'';
}

54
utils/qemu-uefi-tpm.nix Normal file
View file

@ -0,0 +1,54 @@
{
pkgs,
...
}:
pkgs.writeShellApplication {
name = "qemu-uefi-tpm";
runtimeInputs = with pkgs; [
qemu
swtpm
];
text =
let
tpmOVMF = pkgs.OVMF.override {
tpmSupport = true;
secureBoot = true;
};
in
''
set -ex
state="/tmp/patos-qemu-$USER"
rm -rf "$state"
mkdir -m 700 "$state"
qemu-img create -f qcow2 -F raw -b "$(readlink -e "$1")" "$state/disk.qcow2" 2G
swtpm socket -d --tpmstate dir="$state" \
--ctrl type=unixio,path="$state/swtpm-sock" \
--tpm2 \
--log file="$state/swtpm.log",level=20
cp ${tpmOVMF.variables} "$state"
chmod 700 "$state/OVMF_VARS.fd"
qemu-system-x86_64 \
-enable-kvm \
-machine q35,accel=kvm \
-cpu host \
-smp 8 \
-m 4G \
-display none \
-chardev "stdio,id=char0,mux=on,logfile=$state/console.log,signal=off" \
-serial chardev:char0 \
-mon chardev=char0 \
-drive "if=pflash,format=raw,unit=0,readonly=on,file=${tpmOVMF.firmware}" \
-drive "if=pflash,format=raw,unit=1,file=$state/OVMF_VARS.fd" \
-chardev socket,id=chrtpm,path="$state/swtpm-sock" \
-tpmdev emulator,id=tpm0,chardev=chrtpm \
-device tpm-tis,tpmdev=tpm0 \
-netdev id=net00,type=user,hostfwd=tcp::10022-:22 \
-device virtio-net-pci,netdev=net00 \
-drive "format=qcow2,file=$state/disk.qcow2"
'';
}