From 5ce3d83f99050c554e65aa340ea7a00f631af76c Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:27:23 +0000 Subject: [PATCH 01/21] build: generate SB varstores in-tree (mkvarstore.py); harness --forward Replace virt-fw-vars + the distro OVMF/AAVMF VARS templates with tools/mkvarstore.py: pure-stdlib Python that builds the enrolled edk2 pflash varstore and the AWS AMZNUEFI v0 blob from stage0's PK/KEK/db. The authenticated-variable timestamp is fixed from SOURCE_DATE_EPOCH, so the output is byte-reproducible (virt-fw-vars stamps wall-clock time). Per-arch flash geometry and the FTW tail are captured from the reference varstores; the AMZNUEFI zlib preset dictionary is vendored under tools/firmware/. qemu-test.sh: add repeatable --forward (host TCP -> guest DNAT). To make the target deterministic, DHCP now hands out exactly one lease, 10.0.2.10; gateway/guest IP are named variables. Co-Authored-By: Claude Opus 5.5 --- tools/build.sh | 27 ++- tools/firmware/amznuefi-v0.dict | Bin 0 -> 11381 bytes tools/mkvarstore.py | 305 ++++++++++++++++++++++++++++++++ tools/qemu-test.sh | 33 ++-- 4 files changed, 339 insertions(+), 26 deletions(-) create mode 100644 tools/firmware/amznuefi-v0.dict create mode 100644 tools/mkvarstore.py diff --git a/tools/build.sh b/tools/build.sh index a6e0d37..479adcf 100755 --- a/tools/build.sh +++ b/tools/build.sh @@ -93,24 +93,19 @@ echo "Disk image created: ${DISK_IMAGE}" ls -lh "${DISK_IMAGE}" # --- Generate Secure Boot variables (OVMF + AWS) from stage0's own keys --- -if [ "${ARCH}" = "x86_64" ]; then - OVMF_VARS_ORIG="/usr/share/OVMF/OVMF_VARS_4M.fd" -else - OVMF_VARS_ORIG="/usr/share/AAVMF/AAVMF_VARS.snakeoil.fd" -fi +# tools/mkvarstore.py builds the whole enrolled varstore (edk2 pflash + AWS +# AMZNUEFI) from scratch in pure-stdlib Python -- no virt-fw-vars, no distro +# firmware template. Only stage0's PK/KEK/db are enrolled, and the output is +# byte-reproducible (auth-variable timestamp fixed from SOURCE_DATE_EPOCH). EFI_VARS_OVMF="${OUTPUT_DIR}/efi-vars.ovmf" EFI_VARS_AWS="${OUTPUT_DIR}/efi-vars.aws" -if [ -f "${OVMF_VARS_ORIG}" ]; then - virt-fw-vars --input "${OVMF_VARS_ORIG}" --output "${EFI_VARS_OVMF}" --output-aws "${EFI_VARS_AWS}" \ - --add-db "$(cat "${KEYDIR}/db.guid")" "${KEYDIR}/db.crt" \ - --add-kek "$(cat "${KEYDIR}/KEK.guid")" "${KEYDIR}/KEK.crt" \ - --set-pk "$(cat "${KEYDIR}/PK.guid")" "${KEYDIR}/PK.crt" \ - --set-true DeployedMode \ - --secure-boot - echo "EFI vars written: ${EFI_VARS_OVMF}" -else - echo "Warning: ${OVMF_VARS_ORIG} not found; skipping EFI vars generation." -fi +python3 "${REPO_ROOT}/tools/mkvarstore.py" --arch "${ARCH}" \ + --pk "${KEYDIR}/PK.crt" --pk-guid "${KEYDIR}/PK.guid" \ + --kek "${KEYDIR}/KEK.crt" --kek-guid "${KEYDIR}/KEK.guid" \ + --db "${KEYDIR}/db.crt" --db-guid "${KEYDIR}/db.guid" \ + --dict "${REPO_ROOT}/tools/firmware/amznuefi-v0.dict" \ + --out-ovmf "${EFI_VARS_OVMF}" --out-aws "${EFI_VARS_AWS}" +echo "EFI vars written: ${EFI_VARS_OVMF}" # Emit os-release so the cloud publishers can name/tag the image. BUILD_ID is # derived from the signed stage0 hash so each build is traceable. diff --git a/tools/firmware/amznuefi-v0.dict b/tools/firmware/amznuefi-v0.dict new file mode 100644 index 0000000000000000000000000000000000000000..058566e4575dbfd16e725ce28297b1c9aa48dcb3 GIT binary patch literal 11381 zcmeHtc|4Tg_xLjlW8YJ<4Q1aRW6M&JJ!IcniOGy@>`Rm-AySeQDvG?NEGd=Zjg-hc zB_(Zd3Q>p>lHz-x8A{Xg_NmwF_t)=wUGv=goO|xQ=bm%!Sssmic#y~76N@mH^f3rZ zDCs_aH&8*&?3Tz`p{el3NQSBR@5d%k`V7(#BPQ-etBbT5V zRB>1qP7IEj4Toi5WZGTl;z}~XGvhG+Cv+Yp96@zJ%dI)Zxy`NF&?pFsg~S>!yO2l_ z1R4+)R3=c-q8J_)@H;aDm4P4E&Yt932k&tgu|r))FmikKAqwORSwg{35CV*1gYN2K z5O@fMVuT=3S`Uf=LSfi-knV*PT_^#7{q|IxVEw;6c=%6dmXmQhPKw-Nn%hEzKIaG? zk}s8apPreS>EfhqdqxqKXT;cJF}xBMWVZlHAZ1$+-jVF)n} zLEZp92-*gYE&%d@=8p!0XGcqekvLHK+l|fI3vCRK8T?bM$Z0-l3T7gM(PV(b8`1+$ zK@bsO@dLk>0G~T(1whDXaQuHTn&FQ|Bm4fnm4ks|y-^2C4lT9VBV$tah^1|*8bpB9 zAXNwkf6Cxl1w5-k>QH~wd2Gozt4Z|(jYoSo?Hu;k z9=$tp@%r`$-~}1bi37Ys&eON|??+FAADLcwSfMJ$>9*aCO2Z&P%dN8zGz7~4I7${m zgHEWU3fUtB;b}jVYRSbcB?H{0|CCd(Xu}3HasmkM-=hMLssl2m732i=69VZ2`9^j{ z1cwjg+!3ta7p#r~g+hT4_x&s*C{=28oduXK5mb8iq)}u6Is#pt^)b{LL$IiJk$&H| zKg^7gRgMvbMa62Y#2~anNJ)=;!3qd0bH&^;5d}v-7i0zYgPe;S6b>mQa<^si&w`hh zB7{Uk6!F2=c}?4m3nic3*A_r(!(@%<7 zf`y`Hu+X}*OflR!&KA2lUM#hdcP$nM`Yz1 zcJ${11tJ2imcscqFMY~&_ZGTX=!vEgb6DoVA@cgv!fHzK{(ywyOV$eA! z0zVy1eSvJW9Mo@6c+q!!xpxp{^z&N>LluoESy-B;bH%>uTzyJ_A0@z*s%*^+&G0|g zw`cyTsFcOQzcyRrx@g!Hh0<5d5%<0QZ^ zf(gSb^Ho@ED3l<)J~1GOyp8PU8brkF1qYER0py@?#7Kc*k;UxFz*bS#R9>N~tV*D6 ziq=#^ns7|q?52X|*)k|rAX~A(?&SLv>2G~1{F-n1u;!{N9UD$xxz${}fzySgyCwyy z7D*Wll5doaQeDH_5k)!6wt)ISFI?aia!1k~Z~gaOv*zo9PMi-6M|hMD>)tis+Ms-6 z`~V;z&9s&BQ=fs*4TjW8`(^6q2Kc|(Xpo$P+^B(I6a|=07T`Z(Hi1I56KIlyjGtv~ zTtlzT;wV@0;lkCQKUx56J^*U~Pyu$J`hhmG$vKk`G5^TmJ)%7k zqcR#)W>68zAtf4A!~jE-5@N<7zq2MR*q07i*Mo6~=KcLAH*O`hu1rte@USIo$#vKP zu#T`O))KaW&2mk1jpGeTK|y|6N=j}4-ikhR2Ct$U#Yf4{i;VOt`O%EtKqbI#fX@Jz z0p{9*u$2O=u0T*x1VHe5MkZhfFfiayDC|1e99}!uhSBk>W~T@Z4gF>cM9YbTN`GAc zgNy@qTllT@{q>CDWCi1AW-usJ6bcKWuzXPV`t|XfE}I+2*%Mp;jx&3K;owE6JHKF9 z_#j*3x~{)d;s@fkM63{!3~Qwm|US zWX&64Ds?c-ybf_OH)$Ez0$grXOP2`ENwp#M{@n_$X+%CzRQ$;GNfp%pnh3GM5k>TS zHaG+|mkT`9TA5*(SM~TVhX;{@_yb`8pCteFI&-Tu-Lt3lCe;t>OPhl}q#&vwukcE) zFt*U7DxuzoM{x7X?y~D^j(ig0%bI%Mm`SNzE>)t}EPJUZ2$#u*^J{7DbSQ1#x1 z-MHmm+J|zc+_zs{zan#b7_$*B}y?cfqj+xg#0?DVUKXnI8M&*EdHf~ zahJ`!iKlq*r~mek$*_UN*tfQ~>6m05^^#dH$HGXDzy5TV5qrLSu4BEE&#soS_a#i1 zxHQ9u_7H*;Muu$Jw$Z~oO{Fg#K6KJq|NPVz39j7E)jj4;O`BORV-sY8NoNlG)5F^y zs6RQyEru>A5_u|768b!66NULU^P6(3O!1oA&S|gd;oBt_?G*O(Pp(^jCgo)0RU%G4 zS1ZCxVn=mzwafVC(bjL^sT!0jDu_??tAd!Y4WNFbVW{^#;y3@gAgcZX{a9cEBP@up z^KY{t8Uw;+I40Un{EY4D$sR@K?!Frn8RRNRteUK%GF*&pwu^qlxa;Z-eB7gndK z%Fg5$D@1M$XPD_;yBe#8_v^mi=hbzzRz3JtlJc_@zuu=B6+uQB(i;+7mdV#VH9qAr zVJ&q$U;tOpR4Jlus}|YYHYin@AT(Xsw2YZjXmp^?H$z9StvPS?CbXx;AX!vGdZYTx zXZ=Mi>0JUB?sQ(`d2wxn)ElWVIC+CCvzPcDTNi%$T9UBsl|j?dW3GF5lb8byHtjfR zC-*FTV$mJ7P2NIs8(XT5E=#8PR!BZl=dHJFmnx|wXzQiPKfif9w7l%WEk;|V0%a7$dErZtF z$AA5B*zMHG5k=%C0g>jnq)0fyi17j-K0WOrRfA8cjUY!{UW+hUH(aaUgzn>QS%Q_WJaoh`E*^^Dw z{zpbO=Tm_5$$^rz;c+$I=mzv)&z66Vh1?!?ORFml*NqELi0ZZ}>^~NPBkx}{M`uew zXR}|@dFv~2$ZFppVHsYU)Nm~|9XN2gyDAWv=0R|Sz3@plsNGmN)1%&1o z1(DS>P`{B?jGP+Nni=??mWdFyVlI-Cnv4-4L@IKaM^9>v;MyXem=z|@y!NB7oKy?= zS!0Vf6~{h~-lfO5|AO#4Oy%g(O@eQ&QYX*b$E}eT!dI7JdM)i|A=x1>Y3+jm9+MoO+ei{E`jUd&uYZiI8~ z2q~c=&7Kf^!ZX%WCr^Sqf2jB&wxqd3*Eu(?^^p121L8}Ag!isA<}fJeDa%$>JNNOT zZJ~V3U_OI?~n}ZpTmEoJpL|eRqC<|rOo@TcBeF?#BR|$@m`U= zEAyUraL+|@g;@MYT+Huxq1qWm21aXITR2Srcdsf zToW&~#QsF=t@YU-;3IZ?1;!Z?N{x~|dg)6yqF483bno7vvugEKWBvg97ZT#<9!2zF z7-jP&L{g3FA@+8GJ>48?Qd=?piwcJCO6BG{Yq)$^k$$-=%=Uq;-Mv>G!&gsE1b8)FtJ&7;9Oc0$XJ{R3aJVMx7Sq_!~tO-0& zap2wJO{@VuHL{?)eRuJ zlU#!kSA*)Fsw%@Oz(-Y9Q_%qKsfva&Oi-I`emmvD;uT1wYt{D>@WmHIVs^+M@T!1` zArILDZ%Yq&VSbFG1gu)tQn_6JmRq+xoWOW?SK#lNG_+Q=uY-{E+pp z!!K28cv?qrxsN}0e~0$?d!kS! zm#>83^5mwopQt*-4aVLo(Ub5y>h)?mmGfbSXm4M-Xt^v~irI{`3|GX&!^l&uA(ae` z;X|CMX-BV3cT#qGb4J{+Gkm6MouSFuyV;>*2}8zvT)~?2xuKt#1m5{O{F4*EEI*;S z;Iq@t`(%$r2X@B1i{kBNPfpTFh#Tl`sn+i;R){;e&r@!Fq`^m=Ec63^<6!;rQ(Lu*9^-f zryA*L#|V0KOzJxmo7t;ALur=pgSG!Uz5J7vo^E)Tf+dTmREV$5PzE`olyf41;jZDe zVq3l#(J2^Pq@nKmcr95_wSzR&j=tla&enFvTRgn@+(;GXq>;<%>$q!Tv2Q=W>klWm z)O4IZCC+DdtFFUrV8?1lwepvi!57M0Fygi)2f~Hhv-Lz5#oPIn|I4n%8Cj+paOJRz z_DJ}^$#S7hC;2ZY+;}B8UU680vLdJZz{jNUBlTpCOL;&B zPo3)HAh)aNrmR}bMj|{ZzsKAqB_Y*$ai!_KLjeWv&FSH}C}&^a8T`Bs)((0fog01R z#ocJRgOq(YgIdH!`Qu4P>ERcz(_-DA-%xfeRmSczOTN7?)JL}zE+0Vt{M3H;!py9a1 zgC0Jq-NgCrp^CAT(xP-$Pgjq#?b{Q5_ZuB_UmPHI!`ZNs9zJE?$vt=aScGtA0*TGi zZ>)#fblzF{^e0Xgw{z4)n+Vavmkg9BTTAf-4jn2|^x)PUQa-)g1J+UzKk`9?`SgSJ zC+Oj?GgqHA4leF^l2#;MacRla-t-ej@}jTu`71XisU%+eL=WGvxUTTr8`&5k>54)@ z^IZ>{k~gqPNejE8aRV>Yu4P2g!#8oNY+HP}Z*tdRJKmi_B44q?xT>g4sn-X#NdqX%Ir!DcItBNKhV<};HycZWS?*jl`J`d9 z!=2}uyG2RI0iD}P%bP5AlRY~30f|Ih4Pflfm&$o*@CC&YK`7|EKsqf=?hTO76L%`& zxi|#vK0%yV#An5W8)Yt2U=5xuKpPJkKn|cPKsF!|YXRC{Gf2w7{l$ZE^b^yP`wSqS z0sSxywXpCP;({aU>St^Jnid8?VEt%n{O1qyNg#5GL|kb!Ay9GtcJ8F7l*oSq%g6`q zI)#l~bzI1@nAl}Qx_hA&i8jyepBDF7h{`qw9P*>E&G&f=95t{CK?A@%qUS_7mf<1D zUDVL>7A&r~5RhO2g^4bJ4#y<^NxtC!GaQwwU;ZIx-47F(|IZl?jydor2g|~{=xh3B zUanJF8`h*5*MuLw$J>#}0q%G!*8q^)v2YFWA_n<+ySfqaND7FS=K(u8B8|7gwsYk++69(NWSEk!?HR`K?RMy9_?=*FTrA>doHpkq-e=oFK;`AtJ+ zPcyds+Jq>^U^ab}oqHF56mBSO2Wxp?4I4|tT0_^|8~h3xZDVq|Qx>M#deNymm3E(B zR<$0xp1&k1N-t@n^DYwM>R#ifH~v*(mRU)WGX|?u_7ln_O-h0*-ZYtutQFYV6PqO* z7HYv(Rz1$y#@|-;QSOxWicMovSDu8SpUe!h2xdIkbyFi_vY%f9xZk?78cI$NC-J z`@mA!_ksA4B*FWC5|jW@ie=a(Fn=_k;Wiun=R2LaYueWxUuMswttIYR2yaBf7@}Bv z*cP_Vwam4MH~XJbPCzyQ%L9G~%no>*mUu#PPioY}lgnJ92_&BEU>n$Kt_>1T20uwW z&E~d%6G}~L{c?sMBt-up0JC?2pMwA`xA3ca?jx2t$N1YX(x_iZd?Qe)qHz%^RRf15 zV|^0OBsJ|N`Av43;mS33v7#G2NbvFQk&(=`mz^CO^u|{tPj53feWjt1rg#J;vVqU) zWnqd0`&j(TGjOvm|Lc@w{&+uqjdv}z2Ri-v_GNPHxoGaQTx4&LlBLAmD~ul+`URGR z1PaIa6m~G&(Q1s4ZdA|XXP4QVnMHbfrq&{*X8l#U)0$@3!$OnlS8r&=V@pc!$3}FW z`PYkco-_&J+mDzdOrIKN|;?ZI!2Y#1Im@uNgw*Fms3XiVeC{3Uu;Baah zUzit*24;#pBeP4q2`c`>8WcNLlwa7=kLYV_YmPT2`VzrcC?L);FTFlbm~>vbbk7K! zV2Q|E^FC#b;)MrC0|r5$?yF4v5a81EZBZZE=R+j zEyb4sD!#;~w}*VEoyeGN9d@tyX3f#341rO7BAUDxUSEWF=mwuTs?XY4c1^Gb?s`96 z`(&%wk?|X)|7u&Bvb+?Tj4xZw-hSUmw%taj<{&lLM1H=U2A$JzG>?vX=qxntkZs?9z|t zHVX9~?yFbj-aVEiC7JK1KFBt{Yh~($`sn27qWh^^|F*qQ+Gbih{64ThBBaMaR^v)c zekPli@^b&&o}Nofn~i&l#P19TyGD2GUovqFxs zEUk%D3js50d@-R=Uy`)*@1UO>_IfA=6hJXQ1Bzh$2GN2eudQGtz4$Ir@Tq~gU#{Zb F{{d^a+4led literal 0 HcmV?d00001 diff --git a/tools/mkvarstore.py b/tools/mkvarstore.py new file mode 100644 index 0000000..8b7b764 --- /dev/null +++ b/tools/mkvarstore.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +# Generate UEFI Secure Boot variable stores from x509 certs, in both the edk2 +# (OVMF/AAVMF pflash) and AWS "AMZNUEFI" (EC2 --uefi-data) container formats. +# +# Pure Python standard library only -- this replaces `virt-fw-vars` (the +# virt-firmware package) in stage0's build so the entire enrolled varstore is +# produced by auditable code we own, byte-reproducibly. Every field below is +# derived from the on-disk edk2 structures (EFI_FIRMWARE_VOLUME_HEADER, +# VARIABLE_STORE_HEADER, AUTHENTICATED_VARIABLE_HEADER, EFI_SIGNATURE_LIST) and +# the AMZNUEFI v0 format (awslabs/python-uefivars); see REPRODUCIBLE-BUILDS.md. +# +# Determinism: unlike virt-fw-vars (which stamps wall-clock time into the +# PK/KEK/db authenticated variables, making its output differ every build), the +# authenticated-variable timestamp here is fixed from SOURCE_DATE_EPOCH. + +import argparse +import base64 +import os +import struct +import sys +import uuid + +# --- Well-known GUIDs (constants from the UEFI spec / edk2) ------------------ +EFI_GLOBAL_VARIABLE = uuid.UUID("8be4df61-93ca-11d2-aa0d-00e098032b8c") +IMAGE_SECURITY_DATABASE = uuid.UUID("d719b2cb-3d3a-4596-a3bc-dad00e67656f") +CUSTOM_MODE_GUID = uuid.UUID("c076ec0c-7028-4399-a072-71ee5c448b9f") +SECURE_BOOT_ENABLE_GUID = uuid.UUID("f0a30bc7-af08-4556-99c4-001009c93a44") +EFI_CERT_X509_GUID = uuid.UUID("a5c059a1-94e4-4aa7-87b5-ab155c2bf072") +EFI_CERT_SHA256_GUID = uuid.UUID("c1c41626-504c-4092-aca9-41f936934328") +NV_DATA_FV_GUID = uuid.UUID("fff12b8d-7696-4c8b-a985-2747075b4f50") +AUTH_VAR_STORE_GUID = uuid.UUID("aaf32c78-947b-439a-a180-2e144ec37792") + +# virt-fw-vars adds a placeholder dbx: sha256("") owned by a fixed GUID, stamped +# 2010-01-01. Reproduced verbatim so our output matches the established shape. +DBX_DUMMY_OWNER = uuid.UUID("a0baa8a3-041d-48a8-bc87-c36d121b5e3d") +SHA256_EMPTY = bytes.fromhex( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + +# UEFI variable attributes +NV, BS, RT, TIME_AUTH = 0x1, 0x2, 0x4, 0x20 +ATTR_PLAIN = NV | BS # 0x03: NV + boot-services +ATTR_AUTH = NV | BS | RT | TIME_AUTH # 0x27: + runtime + time-based auth + +# edk2 variable-store state/format bytes +VAR_ADDED = 0x3f # AUTHENTICATED_VARIABLE_HEADER.State for a live variable +VS_FORMATTED = 0x5a # VARIABLE_STORE_HEADER.Format +VS_HEALTHY = 0xfe # VARIABLE_STORE_HEADER.State +VAR_START_ID = 0x55aa + + +# --- EFI_TIME --------------------------------------------------------------- +def efi_time(epoch): + """16-byte EFI_TIME from a UNIX epoch (UTC), nanosecond/timezone/daylight 0.""" + import time + t = time.gmtime(epoch) + return struct.pack("> 1) ^ (0x82f63b78 & -(c & 1)) + _CRC32C_TABLE.append(c & 0xffffffff) + for b in data: + crc = _CRC32C_TABLE[(crc ^ b) & 0xff] ^ (crc >> 8) + return crc ^ 0xffffffff + + +def serialize_aws(varlist, dict_path): + import zlib + zdict = open(dict_path, "rb").read() + raw = bytearray() + raw += struct.pack(".sig is served too if present). --serve-dir Serve this whole directory at http://10.0.2.1:8000/ instead of a single payload (e.g. UKI + stage2). + --forward Forward a host TCP port to the guest (10.0.2.10). + Repeatable (e.g. --forward 8402 --forward 9090). --trace Capture guest TCP on tap0 to a pcap (see --trace-file). --trace-file pcap output path (default: ./stage0-trace.pcap). -h, --help Show this help. @@ -69,6 +71,7 @@ PAYLOAD="" SERVE_DIR="" TRACE=0 TRACE_FILE="" +FORWARD_PORTS=() while [ $# -gt 0 ]; do case "$1" in @@ -81,6 +84,7 @@ while [ $# -gt 0 ]; do --serve-dir) SERVE_DIR="$2"; shift 2 ;; --trace) TRACE=1; shift ;; --trace-file) TRACE_FILE="$2"; shift 2 ;; + --forward) FORWARD_PORTS+=("$2"); shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "Unknown option: $1" >&2; usage; exit 1 ;; esac @@ -230,10 +234,13 @@ trap cleanup EXIT INT TERM echo "Press Ctrl-A, then X to exit QEMU" -# --- Guest network: tap0 (10.0.2.1 gw + 169.254.169.254 IMDS), NAT out ------ +# --- Guest network: tap0 (gateway + 169.254.169.254 IMDS), NAT out ----------- +GUEST_GW=10.0.2.1 +GUEST_IP=10.0.2.10 + ip tuntap add dev tap0 mode tap ip link set tap0 up -ip addr add 10.0.2.1/24 dev tap0 +ip addr add ${GUEST_GW}/24 dev tap0 ip addr add 169.254.169.254/24 dev tap0 if [ "${TRACE}" = 1 ]; then @@ -265,27 +272,33 @@ fi if [ -n "${SERVE_ROOT}" ]; then # HTTP/1.1 (Content-Length + keep-alive). The stdlib default is HTTP/1.0 # Connection: close, which OVMF's HttpDxe never completes the response token for. - ( cd "${SERVE_ROOT}" && exec python3 -c 'import http.server; http.server.SimpleHTTPRequestHandler.protocol_version="HTTP/1.1"; http.server.ThreadingHTTPServer(("10.0.2.1",8000), http.server.SimpleHTTPRequestHandler).serve_forever()' ) & + ( cd "${SERVE_ROOT}" && exec python3 -c "import http.server; http.server.SimpleHTTPRequestHandler.protocol_version='HTTP/1.1'; http.server.ThreadingHTTPServer(('${GUEST_GW}',8000), http.server.SimpleHTTPRequestHandler).serve_forever()" ) & echo $! > "${TMP}/payload-http.pid" - echo "Serving ${SERVE_ROOT} (HTTP/1.1) at http://10.0.2.1:8000/ :" + echo "Serving ${SERVE_ROOT} (HTTP/1.1) at http://${GUEST_GW}:8000/ :" ls -l "${SERVE_ROOT}" | sed 's/^/ /' fi echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE +for fwd_port in "${FORWARD_PORTS[@]}"; do + iptables -t nat -A PREROUTING -i eth0 -p tcp --dport "${fwd_port}" -j DNAT --to-destination ${GUEST_IP}:"${fwd_port}" + iptables -A FORWARD -i eth0 -p tcp -d ${GUEST_IP} --dport "${fwd_port}" -j ACCEPT + echo "Forwarding port ${fwd_port} -> ${GUEST_IP}:${fwd_port}" +done + # dnsmasq: EC2-style DHCP/DNS (gateway, DNS, classless route to IMDS, hostnames), # plus payload.lockboot.test -> 10.0.2.1 so hostname URLs exercise EFI_DNS4. { - for i in $(seq 10 20); do echo "10.0.2.${i} ip-10-0-2-${i}"; done - echo "10.0.2.1 payload.lockboot.test" + echo "${GUEST_IP} ip-${GUEST_IP//./-}" + echo "${GUEST_GW} payload.lockboot.test" } > "${TMP}/dnsmasq-hosts" dnsmasq --interface=tap0 --bind-interfaces \ - --dhcp-range=10.0.2.10,10.0.2.20,12h \ - --dhcp-option=3,10.0.2.1 \ - --dhcp-option=6,10.0.2.1,8.8.8.8 \ + --dhcp-range=${GUEST_IP},${GUEST_IP},12h \ + --dhcp-option=3,${GUEST_GW} \ + --dhcp-option=6,${GUEST_GW},8.8.8.8 \ --dhcp-option=15,ec2.internal \ - --dhcp-option=option:classless-static-route,169.254.169.254/32,10.0.2.1 \ + --dhcp-option=option:classless-static-route,169.254.169.254/32,${GUEST_GW} \ --dhcp-option=119,ec2.internal,local.compute.internal \ --domain=ec2.internal \ --expand-hosts \ From 92577055ed9bbe21952a520941ed89518cb8c4cd Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:36:08 +0000 Subject: [PATCH 02/21] Dockerfile.build: drop virt-firmware and python3-pip stage0 now builds its Secure Boot varstores with tools/mkvarstore.py (stdlib only), so nothing runs virt-fw-vars, and pip was installed only for it. Canonical copy; synced to stage1, stage2 and vaportpm with `make sync-harness` in the workspace. Co-Authored-By: Claude Opus 5.5 --- Dockerfile.build | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Dockerfile.build b/Dockerfile.build index f9df7d5..f9f73b1 100644 --- a/Dockerfile.build +++ b/Dockerfile.build @@ -22,7 +22,6 @@ RUN apt-get -qq update && \ openssl \ ovmf \ python3 \ - python3-pip \ qemu-efi-aarch64 \ rpm \ rpm2cpio \ @@ -30,8 +29,7 @@ RUN apt-get -qq update && \ util-linux \ uuid-runtime \ wget \ - xz-utils && \ - pip3 install --break-system-packages virt-firmware + xz-utils # Reproducible builds environment ENV SOURCE_DATE_EPOCH=0 From 305ef855a83b73abad0b48dacceaf3b0c2b1d276 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:53:11 +0000 Subject: [PATCH 03/21] harness: pin, multi-arch (host-aware KVM/TCG + mock), publish per release The QEMU harness is an end-user artifact, and its OVMF/AAVMF CODE images boot the varstores mkvarstore.py lays out for bookworm's pflash geometry, so it must not drift from the stage0 release it ships with. - Pin debian:bookworm-slim by index digest. - EC2 metadata mock per arch: the image selects it by TARGETARCH, qemu-test.sh by host `uname -m` (arm64 sha256 from the upstream v1.13.0 asset; amd64 unchanged). - qemu-test.sh: KVM when host arch == guest arch (aarch64 guest on an arm64 host: -cpu host, gic-version=host), TCG otherwise. x86_64 hosts behave exactly as before. - release-harness job on stage0-v* (after release-stage0): multi-arch (amd64 + arm64) push to ghcr with provenance + SBOM + attestation, and the digest appended to that release's notes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 80 +++++++++++++++++++++++++++++++++++++ Dockerfile.harness | 30 +++++++++----- tools/qemu-test.sh | 34 +++++++++++----- 3 files changed, 126 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ca6425a..09c1da9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -94,3 +94,83 @@ jobs: prerelease: true generate_release_notes: true make_latest: true + + # ---- QEMU test-harness image (tag: stage0-v*) ----------------------------- + # End-user harness: qemu + swtpm + OVMF/AAVMF + the EC2 metadata mock, qemu-test.sh as entrypoint. + # Published with the stage0 release it ships beside: its firmware boots that release's efi-vars. + # Multi-arch so it runs identically on amd64 and arm64 hosts (KVM when host == guest arch, TCG + # otherwise). Consumers pin the digest appended to the release notes below, not the tag. + release-harness: + runs-on: ubuntu-latest + needs: release-stage0 + if: startsWith(github.ref, 'refs/tags/stage0-v') + permissions: + contents: write + packages: write + id-token: write + attestations: write + + steps: + - name: Checkout repository + uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + + - name: Set up QEMU (arm64 layers on the amd64 runner) + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata for Docker + id: meta + uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 + with: + images: ghcr.io/${{ github.repository }}-harness + tags: | + type=ref,event=tag + flavor: | + latest=false + + - name: Build and push multi-arch harness + id: push + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + with: + context: . + file: ./Dockerfile.harness + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + annotations: ${{ steps.meta.outputs.annotations }} + provenance: true + sbom: true + + - name: Attest harness image + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0 + with: + subject-name: ghcr.io/${{ github.repository }}-harness + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true + + - name: Append image digest to the release notes + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.ref_name }} + DIGEST: ${{ steps.push.outputs.digest }} + run: | + gh release view "$TAG" -R "${{ github.repository }}" --json body -q .body > notes.md + { + echo + echo "### Test harness image" + echo + echo '```' + echo "ghcr.io/${{ github.repository }}-harness@${DIGEST}" + echo '```' + } >> notes.md + gh release edit "$TAG" -R "${{ github.repository }}" --notes-file notes.md diff --git a/Dockerfile.harness b/Dockerfile.harness index 1e4fe60..a5638da 100644 --- a/Dockerfile.harness +++ b/Dockerfile.harness @@ -1,6 +1,10 @@ # Lean QEMU test-harness runtime for qemu-test.sh: no rust/sbsign/kernel toolchain, # just the qemu/swtpm layer needed to boot a disk and mock the metadata service. -FROM debian:bookworm-slim +# Pinned by digest (multi-arch index): the OVMF/AAVMF CODE images here are what boot the varstores +# tools/mkvarstore.py lays out for bookworm's pflash geometry, so the firmware must not drift. +# Published multi-arch (linux/amd64 + linux/arm64) to ghcr on stage0-v* tags, alongside the +# stage0 release it was built with. +FROM debian:bookworm-slim@sha256:99c0b25c46d0214d5a2091092e7908907dcaecd6a962cde0ac700acee222b6f3 RUN apt-get -qq update && \ apt-get install -y --no-install-recommends \ @@ -22,15 +26,23 @@ RUN apt-get -qq update && \ tcpdump && \ rm -rf /var/lib/apt/lists/* -# Pre-bake the EC2 metadata mock so make/CI runs don't download into the -# bind-mounted repo. qemu-test.sh checks EC2_MOCK_CACHE (set to /opt by the -# Makefile) before falling back to its own download. +# Pre-bake the EC2 metadata mock for the image's arch so make/CI runs don't download into the +# bind-mounted repo. qemu-test.sh checks EC2_MOCK_CACHE (set to /opt by the Makefile) before +# falling back to its own download; hashes match the ones in qemu-test.sh. +ARG TARGETARCH ARG AEMM_VERSION=v1.13.0 -ARG AEMM_SHA256=4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950 -RUN curl -fsSL -o /opt/ec2-metadata-mock-linux-amd64 \ - "https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-amd64" && \ - echo "${AEMM_SHA256} /opt/ec2-metadata-mock-linux-amd64" | sha256sum -c - && \ - chmod +x /opt/ec2-metadata-mock-linux-amd64 +ARG AEMM_SHA256_amd64=4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950 +ARG AEMM_SHA256_arm64=9dae5b5849365dbaa133309da81f49bafe94ec0aa7e6b05ce3eb7a8f151c2217 +RUN case "${TARGETARCH}" in \ + amd64) sha="${AEMM_SHA256_amd64}" ;; \ + arm64) sha="${AEMM_SHA256_arm64}" ;; \ + *) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \ + esac && \ + f=/opt/ec2-metadata-mock-linux-${TARGETARCH} && \ + curl -fsSL -o "$f" \ + "https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-${TARGETARCH}" && \ + echo "${sha} $f" | sha256sum -c - && \ + chmod +x "$f" # The mock is baked at /opt; point the entrypoint script at it by default. ENV EC2_MOCK_CACHE=/opt diff --git a/tools/qemu-test.sh b/tools/qemu-test.sh index 81a644f..151dc9f 100755 --- a/tools/qemu-test.sh +++ b/tools/qemu-test.sh @@ -20,13 +20,21 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TMP=/tmp -# EC2 metadata mock (downloaded + sha256-verified on first run; cached next to the -# script, override the cache dir with EC2_MOCK_CACHE). +# Host arch (where QEMU runs), as opposed to ARCH (the guest). Both amd64 and arm64 hosts are +# supported for both guests: KVM when they match, TCG emulation otherwise. +HOST_ARCH="$(uname -m)" +case "${HOST_ARCH}" in + x86_64) AEMM_ARCH=amd64; AEMM_SHA256="4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950" ;; + aarch64) AEMM_ARCH=arm64; AEMM_SHA256="9dae5b5849365dbaa133309da81f49bafe94ec0aa7e6b05ce3eb7a8f151c2217" ;; + *) echo "Error: unsupported host arch ${HOST_ARCH} (need x86_64 or aarch64)" >&2; exit 1 ;; +esac + +# EC2 metadata mock for the host arch (downloaded + sha256-verified on first run; cached next to +# the script, override the cache dir with EC2_MOCK_CACHE). AEMM_VERSION="v1.13.0" -AEMM_URL="https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-amd64" -AEMM_SHA256="4f89ddc71ac53ce540bda1f9c340526d558eed8e41349761f2798acf1b254950" +AEMM_URL="https://github.com/aws/amazon-ec2-metadata-mock/releases/download/${AEMM_VERSION}/ec2-metadata-mock-linux-${AEMM_ARCH}" EC2_MOCK_CACHE="${EC2_MOCK_CACHE:-${SCRIPT_DIR}}" -AMMM="${EC2_MOCK_CACHE}/ec2-metadata-mock-linux-amd64" +AMMM="${EC2_MOCK_CACHE}/ec2-metadata-mock-linux-${AEMM_ARCH}" usage() { cat <<'EOF' @@ -186,7 +194,8 @@ if [ "${ARCH}" = "x86_64" ]; then QEMU_CMD="qemu-system-x86_64" QEMU_MACHINE="-machine q35,smm=on" QEMU_CPU="" - QEMU_EXTRA="-enable-kvm" + # KVM on a matching host (unchanged: fails loudly without /dev/kvm); TCG on an arm64 host. + [ "${HOST_ARCH}" = "x86_64" ] && QEMU_EXTRA="-enable-kvm" || QEMU_EXTRA="" QEMU_SERIAL="-serial none" QEMU_SERIAL_DEVICE="-device isa-serial,chardev=char0" TPM_DEVICE="tpm-tis" @@ -194,9 +203,16 @@ if [ "${ARCH}" = "x86_64" ]; then else OVMF_CODE="/usr/share/AAVMF/AAVMF_CODE.fd" QEMU_CMD="qemu-system-aarch64" - QEMU_MACHINE="-machine virt" - QEMU_CPU="-cpu cortex-a72" - QEMU_EXTRA="" + if [ "${HOST_ARCH}" = "aarch64" ]; then + # KVM on a matching host: the guest takes the host's CPU + GIC. + QEMU_MACHINE="-machine virt,gic-version=host" + QEMU_CPU="-cpu host" + QEMU_EXTRA="-enable-kvm" + else + QEMU_MACHINE="-machine virt" + QEMU_CPU="-cpu cortex-a72" + QEMU_EXTRA="" + fi QEMU_SERIAL="-serial none" QEMU_SERIAL_DEVICE="-device pci-serial,id=serial0,chardev=char0" TPM_DEVICE="tpm-tis-device" From e6dfd035a002ab189fce49fa87d5f572abe25f16 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:34:00 +0000 Subject: [PATCH 04/21] harness: probe vTPM provisioning via getcap (nvreadpublic segfaults) tpm2-tools 5.4 (bookworm) tpm2_nvreadpublic SEGFAULTs on an undefined NV index (exit 139). The provisioning probe treated that as "not yet provisioned" and carried on, so tests passed, but every fresh-TPM boot dumped a root-owned 0600 `core` into the caller's cwd (the repo; the host core_pattern is a bare `core`). List the NV handles with tpm2_getcap handles-nv-index instead. Verified: a fresh-TPM boot provisions, reaches `payload: done`, and leaves no core file. Co-Authored-By: Claude Opus 5.5 --- tools/qemu-test.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/qemu-test.sh b/tools/qemu-test.sh index 151dc9f..f646b30 100755 --- a/tools/qemu-test.sh +++ b/tools/qemu-test.sh @@ -156,7 +156,9 @@ provision_tpm() { tpm2_startup -c local NV_ECC_CERT=0x01c10002 NV_ECC_TEMPLATE=0x01c10003 - if tpm2_nvreadpublic ${NV_ECC_TEMPLATE} >/dev/null 2>&1; then + # Probe via the NV handle list: tpm2-tools 5.4's tpm2_nvreadpublic SEGFAULTs on an undefined + # index (exit 139), which dumped a root-owned `core` into the caller's cwd on every fresh boot. + if tpm2_getcap handles-nv-index | grep -qix -- "- $(printf '0x%X' $((NV_ECC_TEMPLATE)))"; then echo "vTPM already provisioned, skipping." tpm2_shutdown; swtpm_ioctl --unix "${sock}.ctrl" -s; rm -rf "${work}"; return fi From 0c7db36e8d892548270cf9061f491241a77b6672 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:34:00 +0000 Subject: [PATCH 05/21] selftest: harness --timeout, aarch64 PL011 capture, selftest- - qemu-test.sh --timeout : bound an unattended boot (timeout(1) around QEMU); a guest that never powers off exits 124 instead of blocking. Opt-in; default unchanged. - qemu-test.sh aarch64: attach the virt board's PL011 (AAVMF UEFI ConOut, i.e. stage0's output) to the same muxed stdio as pci-serial, so the whole chain is captured as on x86. Kernel printk now appears twice (console=ttyAMA0 console=ttyS0); /dev/console is still ttyS0. Without this, stage0's aarch64 boot matrix could never PASS. - Makefile: HARNESS_TIMEOUT passes --timeout through; selftest- runs the smoke-boot matrix with a 300 s bound (~3x the slowest boot measured on either arch). Part of the workspace `make selftest`. Co-Authored-By: Claude Opus 5.5 --- Makefile | 14 +++++++++++++- tools/qemu-test.sh | 24 +++++++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 7ad2905..78cb4d4 100644 --- a/Makefile +++ b/Makefile @@ -132,9 +132,10 @@ build/%/args.json.sig: build/keys/release.pem | sign-bin # ---- QEMU harness: the lean harness image bakes qemu-test.sh as its entrypoint # (and the EC2_MOCK_CACHE + iptables-ack env), so we just append CLI args. ---- +# HARNESS_TIMEOUT= bounds each boot (qemu-test.sh --timeout); unset = no limit. STAGE0_QEMU = $(DOCKER_RUN) $(DOCKER_OPT_KVM) \ --cap-add=NET_ADMIN --device=/dev/net/tun \ - $(HARNESS_IMAGE) + $(HARNESS_IMAGE) $(if $(HARNESS_TIMEOUT),--timeout $(HARNESS_TIMEOUT)) # Boot stage0 under QEMU. Serves a staging dir (so payload, signed args, and a signed # manifest are all served uniformly at http://SERVE_HOST/) and regenerates the @@ -220,6 +221,17 @@ smoke-boot-%: build/%/boot.disk build/%/payload.efi build/%/args.json.sig docker smoke-boot: smoke-boot-$(ARCH) +# ---- Self-test: stage0's part of the workspace `make selftest` (PASS/FAIL, non-zero on FAIL). +# The boot-test matrix above, with every boot time-bounded so a hang fails instead of blocking. +# One bound for both arches (~3x the slowest measured boot; aarch64 is TCG-emulated but fast). +SELFTEST_TIMEOUT_x86_64 ?= 300 +SELFTEST_TIMEOUT_aarch64 ?= 300 +.PHONY: selftest +selftest: + @echo "needs an arch suffix, e.g. 'make selftest-x86_64'." >&2; exit 2 +selftest-%: + $(MAKE) --no-print-directory smoke-boot-$* HARNESS_TIMEOUT=$(SELFTEST_TIMEOUT_$*) + # Arch-less convenience forms target the host architecture ($(ARCH)). .PHONY: build boot test build: build-$(ARCH) diff --git a/tools/qemu-test.sh b/tools/qemu-test.sh index f646b30..7a11caa 100755 --- a/tools/qemu-test.sh +++ b/tools/qemu-test.sh @@ -60,6 +60,8 @@ Options: instead of a single payload (e.g. UKI + stage2). --forward Forward a host TCP port to the guest (10.0.2.10). Repeatable (e.g. --forward 8402 --forward 9090). + --timeout Kill QEMU if the guest has not powered off by then, and + exit 124 (default: 0 = no limit). For unattended runs. --trace Capture guest TCP on tap0 to a pcap (see --trace-file). --trace-file pcap output path (default: ./stage0-trace.pcap). -h, --help Show this help. @@ -80,6 +82,7 @@ SERVE_DIR="" TRACE=0 TRACE_FILE="" FORWARD_PORTS=() +TIMEOUT=0 while [ $# -gt 0 ]; do case "$1" in @@ -93,6 +96,7 @@ while [ $# -gt 0 ]; do --trace) TRACE=1; shift ;; --trace-file) TRACE_FILE="$2"; shift 2 ;; --forward) FORWARD_PORTS+=("$2"); shift 2 ;; + --timeout) TIMEOUT="$2"; shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "Unknown option: $1" >&2; usage; exit 1 ;; esac @@ -215,7 +219,11 @@ else QEMU_CPU="-cpu cortex-a72" QEMU_EXTRA="" fi - QEMU_SERIAL="-serial none" + # The virt board's PL011 carries AAVMF's UEFI ConOut (stage0's output). Attach it to the same + # muxed stdio as the pci-serial (ttyS0, where /dev/console lands) so the whole chain -- UEFI, + # kernel, init, userspace -- is captured, as it is on x86 via isa-serial. Kernel printk then + # appears on both (console=ttyAMA0 console=ttyS0), i.e. twice in this log. + QEMU_SERIAL="-serial chardev:char0" QEMU_SERIAL_DEVICE="-device pci-serial,id=serial0,chardev=char0" TPM_DEVICE="tpm-tis-device" PFLASH_SECURE="" @@ -323,8 +331,13 @@ dnsmasq --interface=tap0 --bind-interfaces \ --addn-hosts="${TMP}/dnsmasq-hosts" \ --log-queries +# --timeout: bound an unattended run. A guest that never powers off is a failure, not a hang. +QEMU_WRAP=() +[ "${TIMEOUT}" != 0 ] && QEMU_WRAP=(timeout --foreground --kill-after=10 "${TIMEOUT}") +QEMU_RC=0 + # shellcheck disable=SC2086 -${QEMU_CMD} \ +"${QEMU_WRAP[@]}" ${QEMU_CMD} \ ${QEMU_CPU} \ ${QEMU_EXTRA} \ ${QEMU_MACHINE} \ @@ -344,4 +357,9 @@ ${QEMU_CMD} \ -chardev stdio,mux=on,id=char0 \ ${QEMU_SERIAL_DEVICE} \ -drive "if=pflash,format=raw,unit=0,file=${OVMF_CODE},readonly=on" \ - -drive "if=pflash,format=raw,unit=1,file=${OVMF_VARS}" || true + -drive "if=pflash,format=raw,unit=1,file=${OVMF_VARS}" || QEMU_RC=$? + +if [ "${TIMEOUT}" != 0 ] && { [ "${QEMU_RC}" = 124 ] || [ "${QEMU_RC}" = 137 ]; }; then + echo "qemu-test: TIMEOUT: guest did not power off within ${TIMEOUT}s" >&2 + exit 124 +fi From 90b550e52548e20c15e1aa9e73c7dd74b0fe50fa Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:37:55 +0000 Subject: [PATCH 06/21] release: tag releases as plain v* The stage0-v* prefix dates from the pre-split lockboot/lockboot repo, where one workflow carried two release tracks (stage0-v* and uki-v*) and the prefix told them apart. Each repo now releases one product, so every release repo uses plain v* (as vaportpm already does). Workflow trigger, release-job ref checks, and docs updated; release asset names are unchanged. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 12 ++++++------ tools/publish/README.md | 4 ++-- tools/publish/ec2/create.sh | 4 ++-- tools/publish/gcp/create.sh | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 09c1da9..9c6ff1d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,8 +3,8 @@ name: build on: push: branches: [main] - # stage0 is the db-signed root of trust; tag stage0-v* to cut a release. - tags: ['stage0-v*'] + # stage0 is the db-signed root of trust; tag v* to cut a release. + tags: ['v*'] pull_request: branches: [main] workflow_dispatch: @@ -49,11 +49,11 @@ jobs: build/${{ matrix.arch }}/*.guid if-no-files-found: error - # ---- Release track (tag: stage0-v*) -------------------------------------- + # ---- Release track (tag: v*) -------------------------------------- release-stage0: runs-on: ubuntu-latest needs: build - if: startsWith(github.ref, 'refs/tags/stage0-v') + if: startsWith(github.ref, 'refs/tags/v') permissions: contents: write id-token: write @@ -95,7 +95,7 @@ jobs: generate_release_notes: true make_latest: true - # ---- QEMU test-harness image (tag: stage0-v*) ----------------------------- + # ---- QEMU test-harness image (tag: v*) ----------------------------- # End-user harness: qemu + swtpm + OVMF/AAVMF + the EC2 metadata mock, qemu-test.sh as entrypoint. # Published with the stage0 release it ships beside: its firmware boots that release's efi-vars. # Multi-arch so it runs identically on amd64 and arm64 hosts (KVM when host == guest arch, TCG @@ -103,7 +103,7 @@ jobs: release-harness: runs-on: ubuntu-latest needs: release-stage0 - if: startsWith(github.ref, 'refs/tags/stage0-v') + if: startsWith(github.ref, 'refs/tags/v') permissions: contents: write packages: write diff --git a/tools/publish/README.md b/tools/publish/README.md index d0e8983..e8efbfc 100644 --- a/tools/publish/README.md +++ b/tools/publish/README.md @@ -20,7 +20,7 @@ Each publisher reads the per-arch build output: | `build//os-release` | both | names/tags the image (`ID`, `VERSION_ID`, `BUILD_ID`) | | `build//{PK,KEK,db}.cer` | GCP | custom Secure Boot keys | -Produce them with `make build-`. Or pass a `stage0-v*` release tag as the +Produce them with `make build-`. Or pass a `v*` release tag as the `version` argument (instead of the default `local`) to download and attestation-verify the published release artifacts. @@ -46,7 +46,7 @@ ec2/create.sh [--region R] [--public|--private] [--no-verify] [-- gcp/create.sh [--project P] [--region R] [--public|--private] [--no-verify] [--manifest F] [version] ``` -- `` is `x86_64` or `aarch64`; `version` is `local` (default) or a `stage0-v*` tag. +- `` is `x86_64` or `aarch64`; `version` is `local` (default) or a `v*` tag. - `--region` default: `ap-southeast-1` (AWS, Singapore) / `asia-southeast1` (GCP, Singapore). Singapore is the always-on default; KL `ap-southeast-5` works but is an opt-in region you must enable on the account first. diff --git a/tools/publish/ec2/create.sh b/tools/publish/ec2/create.sh index b46a081..3fb3be2 100755 --- a/tools/publish/ec2/create.sh +++ b/tools/publish/ec2/create.sh @@ -22,7 +22,7 @@ Build (or download) a stage0 boot disk and register it as an AMI. Arguments: arch x86_64 | aarch64 - version a stage0-v* release tag, or 'local' (default) for a local build + version a v* release tag, or 'local' (default) for a local build Options: --region AWS region (default: ${DEFAULT_REGION}) @@ -41,7 +41,7 @@ Options: Examples: $(basename "$0") x86_64 # local build -> public AMI in ${DEFAULT_REGION} - $(basename "$0") --region us-east-1 x86_64 stage0-v0.1.0 + $(basename "$0") --region us-east-1 x86_64 v0.1.0 $(basename "$0") --private aarch64 EOF } diff --git a/tools/publish/gcp/create.sh b/tools/publish/gcp/create.sh index 90210c6..818e2d0 100755 --- a/tools/publish/gcp/create.sh +++ b/tools/publish/gcp/create.sh @@ -23,7 +23,7 @@ Build (or download) a stage0 boot disk and create a GCP image from it. Arguments: arch x86_64 | aarch64 - version a stage0-v* release tag, or 'local' (default) for a local build + version a v* release tag, or 'local' (default) for a local build Options: --project

GCP project (default: active gcloud project) @@ -38,7 +38,7 @@ Options: Examples: $(basename "$0") x86_64 # active project, public image in ${DEFAULT_REGION} - $(basename "$0") --project my-proj x86_64 stage0-v0.1.0 + $(basename "$0") --project my-proj x86_64 v0.1.0 $(basename "$0") --private aarch64 EOF } From cbc0173a9f5f5f8f162a01033107dde0f249e262 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:54:35 +0000 Subject: [PATCH 07/21] release: attest the files inside the release zips (+ qemu-test.sh) The release attestation covered only the GitHub artifact zips. A consumer can verify a zip and extract from it, but could not verify an extracted file on its own. The release job now unzips both arches and attests, in the same single attestation step, the zips plus every file inside them, and tools/qemu-test.sh, which was released but not attested. Subjects come from a sha256sum-format checksums file (subject-checksums), named /, so the per-arch copies of same-named files stay distinguishable; verification matches by digest. xargs -r keeps an empty listing from hashing stdin. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9c6ff1d..039e732 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -73,12 +73,27 @@ jobs: gh api repos/${{ github.repository }}/actions/artifacts/${ARTIFACT_ID}/zip > stage0-${arch}.zip done - - name: Attest stage0 zips + # One attestation covering the release zips, every file inside them, and the released + # harness script. Consumers can verify a zip and extract from it, or verify an extracted file + # on its own (`gh attestation verify BOOTX64.EFI --repo ...`). Subjects are named via a + # checksums file so the per-arch copies of same-named files stay distinguishable + # (x86_64/... vs aarch64/...); verification itself matches by digest. + - name: List attestation subjects (zips + their contents + qemu-test.sh) + run: | + for arch in x86_64 aarch64; do + mkdir -p "contents/$arch" && unzip -q "stage0-$arch.zip" -d "contents/$arch" + done + { + sha256sum stage0-x86_64.zip stage0-aarch64.zip + (cd tools && sha256sum qemu-test.sh) + (cd contents && find . -type f -printf '%P\n' | LC_ALL=C sort | xargs -r -d '\n' sha256sum) + } > subjects.sha256 + cat subjects.sha256 + + - name: Attest stage0 zips, their contents, and qemu-test.sh uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3.0.0 with: - subject-path: | - stage0-x86_64.zip - stage0-aarch64.zip + subject-checksums: subjects.sha256 - name: Create stage0 release uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1 From faa86047165150733925ec7c3624a93feddb7070 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:40:26 +0000 Subject: [PATCH 08/21] publish: fix teardown safety, GCP image reuse, SNP/t2a launch, console follow - gcp/create.sh: image name includes BUILD_ID (as the EC2 AMI name does), so a rebuild with the same VERSION_ID (new keys/binary) makes a new image instead of silently reusing a stale one. - ec2/create.sh, gcp/create.sh: record a resource in --manifest only when this run created it; reused snapshots/AMIs/GCS objects/images may belong to an earlier session and must not be swept by this run's teardown. - gcp/launch-instance.sh: n2d -> SEV_SNP + --min-cpu-platform="AMD Milan" (was SEV); c2d -> SEV; c3 -> TDX; t2a -> Shielded VM only (was the deprecated --confidential-compute = SEV; GCP documents no Arm CVM series), a confidential type can be passed as a trailing option for experiments. --no-service-account --no-scopes (the guest never calls GCP APIs). Unknown machine families are refused instead of an interactive prompt. Optional leading --manifest records the instance. - ec2/launch.sh: --manifest records the instance; --tail-timeout bounds --tail (pivot-init keeps the instance running, so it never powers off). - cleanup.sh: aws/gcp instance kinds (terminate / delete), processed first since they are recorded last. - gcp/get-console.sh --follow: --start is a byte index; resume from the response's `next` offset instead of a running line count. - README: launch flags and machine-type table updated to match. Co-Authored-By: Claude Opus 5.5 --- tools/publish/README.md | 18 +++-- tools/publish/cleanup.sh | 6 +- tools/publish/ec2/create.sh | 6 +- tools/publish/ec2/launch.sh | 17 ++++ tools/publish/gcp/create.sh | 13 ++- tools/publish/gcp/get-console.sh | 18 +++-- tools/publish/gcp/launch-instance.sh | 114 +++++++++++---------------- 7 files changed, 103 insertions(+), 89 deletions(-) diff --git a/tools/publish/README.md b/tools/publish/README.md index e8efbfc..064da21 100644 --- a/tools/publish/README.md +++ b/tools/publish/README.md @@ -114,8 +114,8 @@ is reused): - `SEV_CAPABLE`, `SEV_SNP_CAPABLE` — x86_64 only; mark the image launchable as an AMD SEV / SEV-SNP Confidential VM. - `GVNIC` — Google Virtual NIC. -- aarch64 gets `UEFI_COMPATIBLE` + `GVNIC` only (ARM confidential compute needs no - guest-OS feature flag). +- aarch64 gets `UEFI_COMPATIBLE` + `GVNIC` only (GCP documents no Arm Confidential VM + series; t2a launches as a Shielded VM). We create the image directly from GCS rather than `gcloud compute images import` because `import` demands a predefined `--os` (e.g. `ubuntu-2204`) and won't set custom @@ -124,11 +124,15 @@ guest-OS features — stage0 is kernel-less, so there is no OS for it to detect. **Trust-model requirement:** Confidential VMs must run with `--maintenance-policy=TERMINATE` (no live migration — migration would expose decrypted guest memory to the hypervisor). Never enable the `SEV_LIVE_MIGRATABLE` feature. -`launch-instance.sh` bakes this in along with `--confidential-compute`, -`--shielded-secure-boot`, `--shielded-vtpm`, and `--shielded-integrity-monitoring`. - -Confidential VM machine types: `n2d-standard-*` (SEV / SEV-SNP), `c2d-standard-*` -(SEV-SNP, compute-optimized), `c3-standard-*` (Intel TDX), `t2a-standard-*` (ARM64). +`launch-instance.sh` bakes this in along with the per-family `--confidential-compute-type`, +`--shielded-secure-boot`, `--shielded-vtpm`, `--shielded-integrity-monitoring`, and +`--no-service-account --no-scopes` (the guest never calls GCP APIs, so it gets no credentials). + +Machine types `launch-instance.sh` accepts: `n2d-standard-*` (SEV-SNP, pinned to +`--min-cpu-platform="AMD Milan"`), `c2d-standard-*` (SEV), `c3-standard-*` (Intel TDX), +`t2a-standard-*` (ARM64, Shielded VM only; pass e.g. `--confidential-compute-type=CCA` as a +trailing option to experiment). Pass `--manifest ` first to record the instance for +`cleanup.sh` -- GCP instances keep running (and billing) after stage0 powers off. How GCP differs from EC2 here: GCP manages the Secure Boot vars and vTPM itself (no `--uefi-data` / `--tpm-support`), memory is encrypted by SEV/SEV-SNP/TDX, and the diff --git a/tools/publish/cleanup.sh b/tools/publish/cleanup.sh index de5e07f..846aada 100755 --- a/tools/publish/cleanup.sh +++ b/tools/publish/cleanup.sh @@ -5,9 +5,11 @@ # snapshot still settling) are warnings, not fatal, so this is safe to re-run. # # Manifest line format: " " +# aws instance i-xxxx (ec2/launch.sh --manifest) # aws ami ami-xxxx # aws snapshot snap-xxxx # aws s3object s3://bucket/key +# gcp instance / (gcp/launch-instance.sh --manifest) # gcp image image-name # gcp gcsobject gs://bucket/path @@ -27,7 +29,7 @@ Options: --dry-run print the delete commands without running them -h, --help show this help and exit -Handles: aws {ami,snapshot,s3object}, gcp {image,gcsobject}. +Handles: aws {instance,ami,snapshot,s3object}, gcp {instance,image,gcsobject}. EOF } @@ -56,9 +58,11 @@ for (( i=${#LINES[@]}-1; i>=0; i-- )); do [ -n "${id:-}" ] || { warn "malformed line: ${line}"; skipped=$((skipped+1)); continue; } case "${provider} ${kind}" in + "aws instance") cli=aws; cmd=(aws ec2 terminate-instances --instance-ids "${id}" --region "${ctx}") ;; "aws ami") cli=aws; cmd=(aws ec2 deregister-image --image-id "${id}" --region "${ctx}") ;; "aws snapshot") cli=aws; cmd=(aws ec2 delete-snapshot --snapshot-id "${id}" --region "${ctx}") ;; "aws s3object") cli=aws; cmd=(aws s3 rm "${id}") ;; + "gcp instance") cli=gcloud; cmd=(gcloud compute instances delete "${id#*/}" --zone "${id%%/*}" --project "${ctx}" --quiet) ;; "gcp image") cli=gcloud; cmd=(gcloud compute images delete "${id}" --project "${ctx}" --quiet) ;; "gcp gcsobject") cli=gcloud; cmd=(gcloud storage rm "${id}" --project "${ctx}") ;; *) warn "unknown resource: ${line}"; skipped=$((skipped+1)); continue ;; diff --git a/tools/publish/ec2/create.sh b/tools/publish/ec2/create.sh index 3fb3be2..d00d7d7 100755 --- a/tools/publish/ec2/create.sh +++ b/tools/publish/ec2/create.sh @@ -181,8 +181,10 @@ else echo "Snapshot created: ${SNAPSHOT_ID}" aws ec2 create-tags --region "${REGION}" --resources "${SNAPSHOT_ID}" \ --tags "Key=Name,Value=${SNAPSHOT_DESC}" "Key=BuildID,Value=${BUILD_ID}" "Key=VersionID,Value=${VERSION_ID}" + # Recorded only when THIS run created it: a reused snapshot/AMI may belong to an earlier + # session and must not be swept by this run's teardown. + record "aws snapshot ${REGION} ${SNAPSHOT_ID}" fi -record "aws snapshot ${REGION} ${SNAPSHOT_ID}" echo "=== Checking for existing AMI ===" EXISTING_AMI=$(aws ec2 describe-images --region "${REGION}" --owners self \ @@ -212,8 +214,8 @@ else echo "AMI registered: ${AMI_ID}" aws ec2 create-tags --region "${REGION}" --resources "${AMI_ID}" \ --tags "Key=Name,Value=${PRETTY_NAME}" "Key=BuildID,Value=${BUILD_ID}" "Key=VersionID,Value=${VERSION_ID}" + record "aws ami ${REGION} ${AMI_ID}" # only when created by this run fi -record "aws ami ${REGION} ${AMI_ID}" # Make the AMI publicly launchable (default; --private opts out): any AWS account # can launch it directly (per-customer config lives in user-data, not the image). diff --git a/tools/publish/ec2/launch.sh b/tools/publish/ec2/launch.sh index d2928b1..74ca7c9 100755 --- a/tools/publish/ec2/launch.sh +++ b/tools/publish/ec2/launch.sh @@ -43,6 +43,11 @@ Options: including a post-mortem drain (EC2's serial buffer lags minutes) --stop STOP (don't terminate) on shutdown, so the instance and its serial console survive for debugging. Default is to terminate. + --tail-timeout with --tail: stop streaming after seconds even if the + instance is still running (default 0 = until it powers off). + The instance is left running; terminate it (or cleanup.sh). + --manifest append the launched instance ("aws instance ") to + for cleanup.sh -h, --help show this help and exit Examples: @@ -57,6 +62,8 @@ INSTANCE_TYPE="" SPOT=false TAIL=false STOP=false +TAIL_TIMEOUT=0 +MANIFEST="" POSITIONAL=() while [ $# -gt 0 ]; do case "$1" in @@ -69,6 +76,10 @@ while [ $# -gt 0 ]; do --spot) SPOT=true; shift ;; --tail) TAIL=true; shift ;; --stop) STOP=true; shift ;; + --tail-timeout) TAIL_TIMEOUT="${2:?--tail-timeout needs a value}"; shift 2 ;; + --tail-timeout=*) TAIL_TIMEOUT="${1#*=}"; shift ;; + --manifest) MANIFEST="${2:?--manifest needs a value}"; shift 2 ;; + --manifest=*) MANIFEST="${1#*=}"; shift ;; -h|--help) usage; exit 0 ;; --) shift; while [ $# -gt 0 ]; do POSITIONAL+=("$1"); shift; done ;; -*) echo "Error: unknown option: $1" >&2; usage; exit 1 ;; @@ -130,6 +141,7 @@ echo "=== Launching ${AMI_ID} (${ARCH}) as ${INSTANCE_TYPE} in ${REGION}${MARKET INSTANCE_ID=$(aws ec2 run-instances "${RUN_ARGS[@]}" \ --query 'Instances[0].InstanceId' --output text) || die "run-instances failed" echo "Launched instance ${INSTANCE_ID} (Name=${NAME}, shutdown=${SHUTDOWN_BEHAVIOR})" +if [ -n "${MANIFEST}" ]; then printf '%s\n' "aws instance ${REGION} ${INSTANCE_ID}" >> "${MANIFEST}"; fi if [ "${TAIL}" = "true" ]; then # Do NOT use `aws ec2 wait instance-running`: stage0 can boot, run, and power off @@ -161,6 +173,7 @@ if [ "${TAIL}" = "true" ]; then echo "Watching ${INSTANCE_ID} state only (no console access; Ctrl-C to stop)..." fi PREV="" + TAIL_START=${SECONDS} DRAIN=0 # extra console fetches after the instance is gone (buffer lags) DRAIN_MAX=12 # ~2 min of post-mortem draining at 10s/poll while :; do @@ -201,6 +214,10 @@ if [ "${TAIL}" = "true" ]; then sleep 10 continue ;; esac + if [ "${TAIL_TIMEOUT}" -gt 0 ] && [ $((SECONDS - TAIL_START)) -ge "${TAIL_TIMEOUT}" ]; then + echo "--- --tail-timeout ${TAIL_TIMEOUT}s reached; instance ${INSTANCE_ID} still ${STATE} (left running) ---" + break + fi sleep 10 done fi diff --git a/tools/publish/gcp/create.sh b/tools/publish/gcp/create.sh index 818e2d0..d03a979 100755 --- a/tools/publish/gcp/create.sh +++ b/tools/publish/gcp/create.sh @@ -154,7 +154,10 @@ source "${OS_RELEASE_FILE}" VERSION_DASH=$(echo "${VERSION_ID}" | tr '.' '-') ARCH_DASH=$(echo "${ARCH}" | tr '_' '-') -IMAGE_NAME="${ID}-${ARCH_DASH}-${VERSION_DASH}" # GCP names: lowercase/digits/hyphens +# GCP names: lowercase/digits/hyphens. BUILD_ID is part of the name (as for the EC2 AMI) so +# re-running after a rebuild -- new keys/binary, same VERSION_ID -- makes a new image instead of +# silently reusing a stale one. +IMAGE_NAME="${ID}-${ARCH_DASH}-${VERSION_DASH}-${BUILD_ID}" IMAGE_DESC="${PRETTY_NAME} version: ${VERSION_ID} build: ${BUILD_ID} arch: ${ARCH}" IMAGE_FAMILY="${ID}" @@ -198,8 +201,10 @@ else ${GCLOUD} storage cp "${TEMP_DIR}/${BUILD_ID}.tar.gz" "${GCS_URI}" --project="${PROJECT}" \ --custom-metadata="version-id=${VERSION_ID},build-id=${BUILD_ID},name=${NAME},pretty-name=${PRETTY_NAME},id=${ID},arch=${ARCH}" \ || die "GCS upload failed" + # Recorded only when THIS run created it: a reused object may belong to an earlier + # session and must not be swept by this run's teardown. + record "gcp gcsobject ${PROJECT} ${GCS_URI}" fi - record "gcp gcsobject ${PROJECT} ${GCS_URI}" echo "=== Creating image ${IMAGE_NAME} (${GCP_ARCH}, ${GUEST_OS_FEATURES}) ===" ${GCLOUD} compute images create "${IMAGE_NAME}" --project="${PROJECT}" \ @@ -210,8 +215,8 @@ else --signature-database-file="${KEYS_DIR}/db.cer" \ || die "image create failed" IMAGE_FINAL="${IMAGE_NAME}" + record "gcp image ${PROJECT} ${IMAGE_FINAL}" # only when created by this run fi -record "gcp image ${PROJECT} ${IMAGE_FINAL}" # Make the image publicly launchable (default; --private opts out): any authenticated # GCP user can create instances from it (per-customer config lives in user-data). @@ -235,7 +240,7 @@ echo "" DEFAULT_ZONE=$(${GCLOUD} config get-value compute/zone 2>/dev/null || echo "") [ -n "${DEFAULT_ZONE}" ] || DEFAULT_ZONE="${REGION}-a" -if [ "${ARCH}" = "aarch64" ]; then MACHINE_TYPE="t2a-standard-1"; TECH="ARM TrustZone"; else MACHINE_TYPE="n2d-standard-2"; TECH="AMD SEV-SNP"; fi +if [ "${ARCH}" = "aarch64" ]; then MACHINE_TYPE="t2a-standard-1"; TECH="Shielded VM, no confidential type"; else MACHINE_TYPE="n2d-standard-2"; TECH="AMD SEV-SNP"; fi echo "Launch a Confidential VM (${TECH}):" echo " ${SCRIPT_DIR}/launch-instance.sh my-instance ${DEFAULT_ZONE} ${MACHINE_TYPE} ${IMAGE_FINAL} config.json" diff --git a/tools/publish/gcp/get-console.sh b/tools/publish/gcp/get-console.sh index 7245ae9..50a4221 100755 --- a/tools/publish/gcp/get-console.sh +++ b/tools/publish/gcp/get-console.sh @@ -54,18 +54,20 @@ case "${MODE}" in echo "Following console output for ${INSTANCE_NAME} (Ctrl+C to stop)..." echo "---" - LAST_LINE=0 + # --start is a BYTE index; resume from the `next` offset each response reports (it also + # stays correct if the serial buffer rolled over and older bytes were dropped). + command -v jq >/dev/null 2>&1 || { echo "Error: --follow needs jq"; exit 1; } + NEXT=0 while true; do - OUTPUT=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ + RESP=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ --zone="${ZONE}" \ --project="${PROJECT}" \ - --start="${LAST_LINE}" 2>/dev/null || echo "") + --start="${NEXT}" --format=json 2>/dev/null || echo "") - if [ -n "${OUTPUT}" ]; then - echo "${OUTPUT}" - # Count total lines to update start position - NEW_LINES=$(echo "${OUTPUT}" | wc -l) - LAST_LINE=$((LAST_LINE + NEW_LINES)) + if [ -n "${RESP}" ]; then + jq -j '.contents // ""' <<<"${RESP}" + N=$(jq -r '.next // empty' <<<"${RESP}") + [ -n "${N}" ] && NEXT="${N}" fi sleep 2 diff --git a/tools/publish/gcp/launch-instance.sh b/tools/publish/gcp/launch-instance.sh index 4bc6b63..8c6934c 100755 --- a/tools/publish/gcp/launch-instance.sh +++ b/tools/publish/gcp/launch-instance.sh @@ -19,8 +19,13 @@ else exit 1 fi +# Optional leading --manifest : append the created instance ("gcp instance +# /") for cleanup.sh. GCP instances do NOT self-delete when stage0 powers off. +MANIFEST="" +if [ "${1:-}" = "--manifest" ]; then MANIFEST="${2:?--manifest needs a value}"; shift 2; fi + if [ $# -lt 5 ]; then - echo "Usage: $0 [additional-options...]" + echo "Usage: $0 [--manifest ] [additional-options...]" echo "" echo "Examples:" echo " # Launch x86_64 instance" @@ -30,9 +35,9 @@ if [ $# -lt 5 ]; then echo " $0 my-vm us-central1-a t2a-standard-1 lockboot-aarch64 config.json --network=my-vpc" echo "" echo "Recommended machine types:" - echo " x86_64 SEV-SNP: n2d-standard-2, n2d-standard-4, c2d-standard-*" + echo " x86_64 SEV-SNP: n2d-standard-2, n2d-standard-4 (SEV only: c2d-standard-*)" echo " x86_64 TDX: c3-standard-*" - echo " aarch64: t2a-standard-1, t2a-standard-2, t2a-standard-4" + echo " aarch64: t2a-standard-1, t2a-standard-2, t2a-standard-4 (Shielded VM, not confidential)" echo "" echo "Common zones: us-central1-a, us-east1-b, europe-west1-b" echo "" @@ -77,22 +82,25 @@ echo "Image: ${IMAGE}" echo "User-data: ${USER_DATA_FILE}" echo "" -# Validate machine type supports Confidential Compute -if [[ "${MACHINE_TYPE}" =~ ^n2d- ]] || [[ "${MACHINE_TYPE}" =~ ^c2d- ]]; then - TECH="AMD SEV-SNP" +# Confidential-compute flags per machine family (non-interactive: unknown families are refused). +# n2d -> SEV-SNP: needs an AMD Milan-or-later host, so pin --min-cpu-platform +# c2d -> SEV +# c3 -> TDX +# t2a -> no documented Arm Confidential VM series: Shielded VM only (secure boot + vTPM + +# integrity). To try a confidential type (experiment G2), pass it in the trailing +# options, e.g. --confidential-compute-type=CCA. +# (The deprecated bare --confidential-compute flag means SEV and is not used.) +if [[ "${MACHINE_TYPE}" =~ ^n2d- ]]; then + TECH="AMD SEV-SNP"; CONF_ARGS=(--confidential-compute-type=SEV_SNP --min-cpu-platform="AMD Milan") +elif [[ "${MACHINE_TYPE}" =~ ^c2d- ]]; then + TECH="AMD SEV"; CONF_ARGS=(--confidential-compute-type=SEV) elif [[ "${MACHINE_TYPE}" =~ ^c3- ]]; then - TECH="Intel TDX" + TECH="Intel TDX"; CONF_ARGS=(--confidential-compute-type=TDX) elif [[ "${MACHINE_TYPE}" =~ ^t2a- ]]; then - TECH="ARM TrustZone" + TECH="none (Shielded VM only)"; CONF_ARGS=() else - echo "Warning: Machine type '${MACHINE_TYPE}' may not support Confidential Computing" - echo "Recommended: n2d-*, c2d-*, c3-*, or t2a-*" - read -p "Continue anyway? (y/N) " -n 1 -r - echo - if [[ ! $REPLY =~ ^[Yy]$ ]]; then - exit 1 - fi - TECH="Unknown" + echo "Error: unsupported machine type '${MACHINE_TYPE}' (use n2d-*, c2d-*, c3-*, or t2a-*)" + exit 1 fi echo "Confidential Compute: ${TECH}" @@ -110,8 +118,9 @@ if [ -n "${EXISTING}" ]; then exit 1 fi -echo "Creating instance with REQUIRED Confidential VM settings:" -echo " ✓ --confidential-compute-type (enables memory encryption)" +echo "Creating instance with REQUIRED settings:" +echo " ✓ ${CONF_ARGS[*]:-(no confidential type: Shielded VM only)}" +echo " ✓ --no-service-account --no-scopes (no cloud credentials reachable from the guest)" echo " ✓ --maintenance-policy=TERMINATE (prevents live migration)" echo " ✓ --shielded-secure-boot (UEFI Secure Boot)" echo " ✓ --shielded-vtpm (virtual TPM 2.0)" @@ -120,55 +129,26 @@ echo " ✓ --boot-disk-type=pd-standard (cheapest, loaded once into memory)" echo " ✓ --boot-disk-auto-delete (cleanup on instance delete)" echo "" -# Determine confidential compute type based on machine type -if [[ "${MACHINE_TYPE}" =~ ^c3- ]]; then - CONF_COMPUTE_TYPE="TDX" -elif [[ "${MACHINE_TYPE}" =~ ^(n2d-|c2d-) ]]; then - CONF_COMPUTE_TYPE="SEV" -elif [[ "${MACHINE_TYPE}" =~ ^t2a- ]]; then - # ARM doesn't need explicit type - CONF_COMPUTE_TYPE="" -else - CONF_COMPUTE_TYPE="SEV" # Default to SEV -fi - -# Launch instance with all required Confidential VM settings -if [ -n "${CONF_COMPUTE_TYPE}" ]; then - ${GCLOUD} compute instances create "${INSTANCE_NAME}" \ - --project="${PROJECT}" \ - --zone="${ZONE}" \ - --machine-type="${MACHINE_TYPE}" \ - --image="${IMAGE}" \ - --network-interface=nic-type=GVNIC \ - --boot-disk-type=pd-standard \ - --boot-disk-auto-delete \ - --metadata-from-file=user-data="${USER_DATA_FILE}" \ - --metadata=serial-port-enable=true \ - --confidential-compute-type="${CONF_COMPUTE_TYPE}" \ - --maintenance-policy=TERMINATE \ - --shielded-secure-boot \ - --shielded-vtpm \ - --shielded-integrity-monitoring \ - "$@" -else - # ARM: use old flag for now (TODO: check if ARM needs specific type) - ${GCLOUD} compute instances create "${INSTANCE_NAME}" \ - --project="${PROJECT}" \ - --zone="${ZONE}" \ - --machine-type="${MACHINE_TYPE}" \ - --image="${IMAGE}" \ - --network-interface=nic-type=GVNIC \ - --boot-disk-type=pd-standard \ - --boot-disk-auto-delete \ - --metadata-from-file=user-data="${USER_DATA_FILE}" \ - --metadata=serial-port-enable=true \ - --confidential-compute \ - --maintenance-policy=TERMINATE \ - --shielded-secure-boot \ - --shielded-vtpm \ - --shielded-integrity-monitoring \ - "$@" -fi +# Launch instance with all required settings. No service account / scopes: stage0..stage2 never +# call GCP APIs, so the guest gets no metadata-server credentials to leak. +${GCLOUD} compute instances create "${INSTANCE_NAME}" \ + --project="${PROJECT}" \ + --zone="${ZONE}" \ + --machine-type="${MACHINE_TYPE}" \ + --image="${IMAGE}" \ + --network-interface=nic-type=GVNIC \ + --boot-disk-type=pd-standard \ + --boot-disk-auto-delete \ + --metadata-from-file=user-data="${USER_DATA_FILE}" \ + --metadata=serial-port-enable=true \ + "${CONF_ARGS[@]}" \ + --maintenance-policy=TERMINATE \ + --shielded-secure-boot \ + --shielded-vtpm \ + --shielded-integrity-monitoring \ + --no-service-account --no-scopes \ + "$@" +if [ -n "${MANIFEST}" ]; then printf '%s\n' "gcp instance ${PROJECT} ${ZONE}/${INSTANCE_NAME}" >> "${MANIFEST}"; fi echo "" echo "=== Instance Created Successfully ===" From be996b47c06120346df06a76e9604c03b8eb50b5 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 15:10:18 +0000 Subject: [PATCH 09/21] stage0: accept User or Deployed Mode; test payload mode probes GCP can only provision PK/KEK/db/dbx (no varstore), so its firmware boots in UEFI User Mode and the DeployedMode==1 gate (11da7ab) refused every GCP boot with SECURITY_VIOLATION. QEMU and EC2 only passed because our own varstore presets DeployedMode=1. - Gate (require_secure_boot_enforcing): SecureBoot==1, SetupMode==0 (absent -> refuse), AuditMode 0 or absent (pre-UEFI-2.5 firmware has no Audit Mode). Admits User and Deployed Mode -- both enforce signatures and only accept PK/KEK-signed key updates; refuses Setup and Audit Mode. Logs the mode. stage0 itself never writes DeployedMode. - stage0-test-payload: prints SecureBoot/SetupMode/AuditMode/DeployedMode (value + attributes, or absent) every boot; --set-deployed tries SetVariable(DeployedMode=1) after the PCR dump (BS|RT, then NV|BS|RT) and reports; --reboot cold-resets instead of powering off, for one PCR dump per boot on one instance. Used to measure whether a User->Deployed transition persists and moves PCR 7 before stage0 ever does it. Co-Authored-By: Claude Opus 5.5 --- crates/stage0-test-payload/src/main.rs | 77 +++++++++++++++++++++++++- crates/stage0/src/main.rs | 47 +++++++++++----- 2 files changed, 109 insertions(+), 15 deletions(-) diff --git a/crates/stage0-test-payload/src/main.rs b/crates/stage0-test-payload/src/main.rs index eaf8f89..78d0966 100644 --- a/crates/stage0-test-payload/src/main.rs +++ b/crates/stage0-test-payload/src/main.rs @@ -23,7 +23,8 @@ use uefi::prelude::*; use uefi::println; use uefi::proto::loaded_image::LoadedImage; use uefi::proto::tcg::v2::Tcg; -use uefi::runtime::{self, ResetType}; +use uefi::runtime::{self, ResetType, VariableAttributes, VariableVendor}; +use uefi::CStr16; use vaportpm_attest::{PcrOps, TpmTransport}; struct Tcg2Transport { @@ -54,11 +55,22 @@ fn main() -> Status { uefi::helpers::init().unwrap(); println!("payload: hello from the chain-loaded UEFI payload"); + // Secure Boot mode variables as the firmware reports them this boot (value + attributes, or + // absent): what stage0's gate saw, and whether the firmware implements the UEFI 2.5 modes. + print_mode_vars(); + match print_pcrs() { Ok(()) => {} Err(e) => println!("payload: could not read PCRs: {e}"), } + // Experiment: attempt the User -> Deployed Mode transition from here (pre-ExitBootServices, + // the same position stage0 would do it from), AFTER this boot's PCRs were dumped, so the next + // boot (`--reboot`) shows whether it persisted and whether PCR 7 moved. + if load_options_contains("--set-deployed") { + set_deployed_mode(); + } + // EC2's serial console buffer is only flushed periodically; if the payload terminates // immediately the PCR dump above never makes it out. Hold ~60s with a heartbeat so it is // visibly alive and the console keeps flushing -- skipped when LoadOptions carry `--nosleep` @@ -75,9 +87,72 @@ fn main() -> Status { // A test payload never boots an OS, so it never needs to hand control back to stage0. Power // off cleanly instead of returning: a return makes stage0 treat it as an unexpected // fall-through and run its own (~90s) fail-closed drain, needlessly slowing the boot. + // `--reboot` cold-resets instead, for one PCR dump per boot on the same instance (cross-boot + // stability). It loops until the instance is stopped/deleted -- bound it externally (e.g. + // GCP --max-run-duration). + if load_options_contains("--reboot") { + println!("payload: --reboot: cold reset"); + runtime::reset(ResetType::COLD, Status::SUCCESS, None) + } runtime::reset(ResetType::SHUTDOWN, Status::SUCCESS, None) } +/// Read a UEFI global variable: `Some((first byte, attributes))`, or `None` if absent/unreadable. +fn global_var(name: &CStr16) -> Option<(u8, VariableAttributes)> { + let mut buf = [0u8; 8]; + runtime::get_variable(name, &VariableVendor::GLOBAL_VARIABLE, &mut buf) + .ok() + .and_then(|(data, attrs)| data.first().map(|b| (*b, attrs))) +} + +/// One line per mode variable: "payload: mode = attrs=0x" or "=absent". +fn print_mode_vars() { + for name in [ + uefi::cstr16!("SecureBoot"), + uefi::cstr16!("SetupMode"), + uefi::cstr16!("AuditMode"), + uefi::cstr16!("DeployedMode"), + ] { + match global_var(name) { + Some((v, a)) => println!("payload: mode {name}={v} attrs=0x{:02x}", a.bits()), + None => println!("payload: mode {name}=absent"), + } + } +} + +/// Try `DeployedMode = 1`, first with the UEFI-spec attributes (BS|RT), then NV|BS|RT; report +/// each SetVariable status and the read-back. Experiment only: says whether the firmware allows +/// the transition from a pre-ExitBootServices image, not whether it is irreversible. +fn set_deployed_mode() { + if matches!(global_var(uefi::cstr16!("DeployedMode")), Some((1, _))) { + println!("payload: --set-deployed: already DeployedMode=1, nothing to do"); + return; + } + let bs_rt = VariableAttributes::BOOTSERVICE_ACCESS | VariableAttributes::RUNTIME_ACCESS; + for (label, attrs) in [ + ("BS|RT", bs_rt), + ("NV|BS|RT", bs_rt | VariableAttributes::NON_VOLATILE), + ] { + let r = runtime::set_variable( + uefi::cstr16!("DeployedMode"), + &VariableVendor::GLOBAL_VARIABLE, + attrs, + &[1u8], + ); + match r { + Ok(()) => { + println!("payload: --set-deployed: SetVariable({label}) = SUCCESS"); + break; + } + Err(e) => println!( + "payload: --set-deployed: SetVariable({label}) = {:?}", + e.status() + ), + } + } + print_mode_vars(); +} + /// True if this image's UEFI LoadOptions (set by stage0 from `_stage1.args` / a signed manifest) /// contain the ASCII `flag`. Lets the QEMU test harness (`--nosleep`) skip the EC2-only /// serial-flush hold. LoadOptions are UCS-2, so an ASCII flag encodes as each byte followed by diff --git a/crates/stage0/src/main.rs b/crates/stage0/src/main.rs index 6348063..367f2c1 100644 --- a/crates/stage0/src/main.rs +++ b/crates/stage0/src/main.rs @@ -87,12 +87,13 @@ fn run() -> Result<(), Status> { crate::slog!("stage0: version: {}", env!("CARGO_PKG_VERSION")); // Fail closed unless the platform is in the state the attestation model assumes: UEFI Secure - // Boot enabled AND Deployed Mode. Enforcing it here means "authentic stage0 ran" -- proven by - // stage0's pinned firmware measurement -- implies the SB/deployed state held, even on firmware - // that does not measure DeployedMode into PCR 7. State only: the release signing cert is - // ephemeral (unknown at build time), so key identity is bound by the per-provider/per-arch - // golden PCR set (PCR 7 == the db), not here. - require_secure_boot_deployed()?; + // Boot enforcing -- SecureBoot on, not in Setup Mode, not in Audit Mode. User and Deployed Mode + // are both accepted (GCP can only provision PK/KEK/db/dbx, so its firmware starts in User + // Mode). Enforcing it here means "authentic stage0 ran" -- proven by stage0's pinned firmware + // measurement -- implies enforcement held. State only: the release signing cert is ephemeral + // (unknown at build time), so key identity is bound by the per-provider/per-arch golden PCR + // set (PCR 7 == SecureBoot/PK/KEK/db/dbx), not here. + require_secure_boot_enforcing()?; // Bring the network up once (DHCP), then fetch metadata. Metadata and payload // both ride the raw-TCP4 HTTP client (http.rs). @@ -145,23 +146,41 @@ fn run() -> Result<(), Status> { Ok(()) } -/// Fail-closed gate: require UEFI Secure Boot enabled AND Deployed Mode, both read straight from -/// the firmware variables (reliable here, pre-ExitBootServices -- unlike later in Linux). Rejects -/// if either is not exactly 1, or the variable is absent (Setup/User/Audit mode, or firmware that -/// does not implement Deployed Mode -- in which case the platform cannot make the guarantee). -fn require_secure_boot_deployed() -> Result<(), Status> { +/// Fail-closed gate on the Secure Boot state, read straight from the firmware variables (reliable +/// here, pre-ExitBootServices -- unlike later in Linux): +/// +/// * `SecureBoot` must be exactly 1; +/// * `SetupMode` must be exactly 0 (absent = cannot tell -> refuse); +/// * `AuditMode` must be 0 or absent (absent: pre-UEFI-2.5 firmware, which has no Audit Mode). +/// +/// That admits User Mode and Deployed Mode, the two modes where signature checks are enforced +/// and the key databases can only change via PK/KEK-signed updates. Setup Mode (no PK, keys +/// writable) and Audit Mode (violations logged, images run) are refused. The mode is logged. +fn require_secure_boot_enforcing() -> Result<(), Status> { if global_var_u8(uefi::cstr16!("SecureBoot")) != Some(1) { crate::slog!("stage0: refusing to boot: UEFI Secure Boot is not enabled"); return Err(Status::SECURITY_VIOLATION); } - if global_var_u8(uefi::cstr16!("DeployedMode")) != Some(1) { - crate::slog!("stage0: refusing to boot: platform is not in UEFI Deployed Mode"); + if global_var_u8(uefi::cstr16!("SetupMode")) != Some(0) { + crate::slog!( + "stage0: refusing to boot: platform is in (or cannot rule out) UEFI Setup Mode" + ); return Err(Status::SECURITY_VIOLATION); } + if !matches!(global_var_u8(uefi::cstr16!("AuditMode")), None | Some(0)) { + crate::slog!("stage0: refusing to boot: platform is in UEFI Audit Mode"); + return Err(Status::SECURITY_VIOLATION); + } + let mode = match global_var_u8(uefi::cstr16!("DeployedMode")) { + Some(1) => "Deployed", + _ => "User", + }; + crate::slog!("stage0: Secure Boot enforcing ({mode} Mode)"); Ok(()) } -/// Read a one-byte UEFI global variable (`SecureBoot` / `DeployedMode` are UINT8). `None` if absent. +/// Read a one-byte UEFI global variable (`SecureBoot` / `SetupMode` / `AuditMode` / +/// `DeployedMode` are UINT8). `None` if absent. fn global_var_u8(name: &CStr16) -> Option { let mut buf = [0u8; 1]; runtime::get_variable(name, &VariableVendor::GLOBAL_VARIABLE, &mut buf) From 34bd6fa31de5a73cdc411514d1e4c1fc743d965f Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:34:51 +0000 Subject: [PATCH 10/21] gvnic: UEFI SNP driver for the Google Virtual NIC, embedded in stage0 GCP's UEFI firmware ships no gVNIC driver -- and no longer a virtio-net one either (its x86 OVMF has the full NetworkPkg stack but no NIC driver), while GCP requires gVNIC for Confidential VMs and Arm. stage0 therefore had no network on any current GCP configuration (`no EFI_IP4_CONFIG2 ... NOT_FOUND`). crates/gvnic is an embedded, measured Driver-Model driver like ena.efi: - GQI_QPL queue format, one TX + one RX queue, polled, no offloads. Protocol derived from the Linux gve driver ((GPL-2.0 OR MIT), used under MIT; reference torvalds/linux 45e0a63f9c86). - Bring-up: version string, admin queue (registered per PCI revision), VERIFY_DRIVER_COMPATIBILITY, DESCRIBE_DEVICE (+ option TLVs, logged), CONFIGURE_DEVICE_RESOURCES, REGISTER_PAGE_LIST x2, CREATE_TX/RX_QUEUE. - TX: frame copied into a fixed 2 KiB TX QPL slot, one packet descriptor; completions from the event counter. RX: QPL page per slot, 3-bit seqno, 2-byte pad; buffers handed back only after copy-out. - MTU from the device (GCP 1460), capped to fit one 2 KiB buffer; SNP MaxPacketSize follows it. - Resets the device at ExitBootServices so RX DMA stops before the OS owns the memory. SNP GetStatus(TxBuf=NULL) does not reap TX completions. - All DMA via PciIo AllocateBuffer + Map(CommonBuffer): correct under SEV. stage0: both drivers embedded via one macro and loaded in a loop; on a missing IPv4 stack, net::bringup() now logs a network inventory (handle counts per layer + every loaded driver's name) before failing closed. Verified on GCP (spot, asia-southeast1-b): Shielded n2d-standard-2, SEV, SEV-SNP (Milan), Shielded c3-standard-4 -- DHCP, DNS, HTTP download, pin verify, payload; PCRs stable across reboots. Idle on local QEMU. TDX (c3) probes OK but passes no traffic -- tracked separately. Co-Authored-By: Claude Opus 5.5 --- Makefile | 22 +- crates/gvnic/Cargo.lock | 142 ++++++ crates/gvnic/Cargo.toml | 23 + crates/gvnic/build.rs | 11 + crates/gvnic/src/binding.rs | 140 ++++++ crates/gvnic/src/device.rs | 921 ++++++++++++++++++++++++++++++++++++ crates/gvnic/src/main.rs | 53 +++ crates/gvnic/src/pci.rs | 160 +++++++ crates/gvnic/src/snp.rs | 318 +++++++++++++ crates/stage0/src/net.rs | 126 +++-- 10 files changed, 1879 insertions(+), 37 deletions(-) create mode 100644 crates/gvnic/Cargo.lock create mode 100644 crates/gvnic/Cargo.toml create mode 100644 crates/gvnic/build.rs create mode 100644 crates/gvnic/src/binding.rs create mode 100644 crates/gvnic/src/device.rs create mode 100644 crates/gvnic/src/main.rs create mode 100644 crates/gvnic/src/pci.rs create mode 100644 crates/gvnic/src/snp.rs diff --git a/Makefile b/Makefile index 78cb4d4..c73d195 100644 --- a/Makefile +++ b/Makefile @@ -53,17 +53,17 @@ sign-test: docker-build-base # ---- CI gate: fmt + clippy + unit tests across all crates (what the branch ruleset requires) ---- # stage0 is not one cargo workspace: 4 independent crates in two target families. The EFI crates -# (ena, stage0, stage0-test-payload) are no_std UEFI and not host-testable -> fmt + clippy on the +# (ena, gvnic, stage0, stage0-test-payload) are no_std UEFI and not host-testable -> fmt + clippy on the # UEFI target; the host signer (stage0-sign) also runs its unit tests (incl. the golden vector). -UEFI_CRATES := ena stage0 stage0-test-payload +UEFI_CRATES := ena gvnic stage0 stage0-test-payload HOST_CRATES := stage0-sign .PHONY: ci fmt-fix fmt-fix: docker-build-base ## Apply rustfmt across all crates (no --check) $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) bash -c '\ for c in $(UEFI_CRATES) $(HOST_CRATES); do cargo fmt --manifest-path crates/$$c/Cargo.toml; done' -# ena.efi is include_bytes!'d by the stage0 crate, so it must exist before clippy/check can +# ena.efi + gvnic.efi are include_bytes!'d by the stage0 crate, so they must exist before clippy/check can # compile it (a clean CI checkout has no build/ artifacts; a warm local tree hid this). -ci: docker-build-base build/x86_64/ena.efi +ci: docker-build-base build/x86_64/ena.efi build/x86_64/gvnic.efi $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) bash -c '\ set -e; rustup target add x86_64-unknown-uefi x86_64-unknown-linux-musl; \ for c in $(UEFI_CRATES) $(HOST_CRATES); do \ @@ -93,12 +93,20 @@ build/%/ena.efi: docker-build-base $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path crates/ena/Cargo.toml --target $*-unknown-uefi && cp -v crates/ena/target/$*-unknown-uefi/release/ena.efi $@" +# ---- Build the gvnic.efi UEFI driver (embedded into stage0 for GCP/gVNIC netboot) ---- +# Same shape as ena.efi, for the Google Virtual NIC: GCP's UEFI firmware ships no gVNIC +# driver, and GCP requires gVNIC for Confidential VMs and Arm. Embedded unconditionally. +.PRECIOUS: build/%/gvnic.efi +build/%/gvnic.efi: docker-build-base + $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ + bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path crates/gvnic/Cargo.toml --target $*-unknown-uefi && cp -v crates/gvnic/target/$*-unknown-uefi/release/gvnic.efi $@" + # ---- Build the stage0 UEFI binary ---- # mkdir runs inside the container (as DOCKER_SAMEUSER) so the output dir is owned # by the build user, not by the host caller (which is root under `gh act`). -# stage0 include_bytes! build/$*/ena.efi unconditionally (one measured unit), so the -# ena.efi prerequisite must be built first; nothing extra to pass on the command line. -build/%/stage0.efi: build/%/ena.efi docker-build-base +# stage0 include_bytes! build/$*/{ena,gvnic}.efi unconditionally (one measured unit), so the +# driver prerequisites must be built first; nothing extra to pass on the command line. +build/%/stage0.efi: build/%/ena.efi build/%/gvnic.efi docker-build-base $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path $(STAGE0_DIR)/Cargo.toml --target $*-unknown-uefi && cp -v $(STAGE0_DIR)/target/$*-unknown-uefi/release/stage0.efi $@" diff --git a/crates/gvnic/Cargo.lock b/crates/gvnic/Cargo.lock new file mode 100644 index 0000000..5c7ef15 --- /dev/null +++ b/crates/gvnic/Cargo.lock @@ -0,0 +1,142 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "gvnic" +version = "0.1.0" +dependencies = [ + "uefi", + "uefi-raw", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "ptr_meta" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b9a0cf95a1196af61d4f1cbdab967179516d9a4a4312af1f31948f8f6224a79" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7347867d0a7e1208d93b46767be83e2b8f978c3dad35f775ac8d8847551d6fe1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "ucs2" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba" +dependencies = [ + "bit_field", +] + +[[package]] +name = "uefi" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7569ceafb898907ff764629bac90ac24ba4203c38c33ef79ee88c74aa35b11" +dependencies = [ + "bitflags", + "cfg-if", + "log", + "ptr_meta", + "ucs2", + "uefi-macros", + "uefi-raw", + "uguid", +] + +[[package]] +name = "uefi-macros" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3dad47b3af8f99116c0f6d4d669c439487d9aaf1c8d9480d686cda6f3a8aa23" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "uefi-raw" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cad96b8baaf1615d3fdd0f03d04a0b487d857c1b51b19dcbfe05e2e3c447b78" +dependencies = [ + "bitflags", + "uguid", +] + +[[package]] +name = "uguid" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab14ea9660d240e7865ce9d54ecdbd1cd9fa5802ae6f4512f093c7907e921533" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" diff --git a/crates/gvnic/Cargo.toml b/crates/gvnic/Cargo.toml new file mode 100644 index 0000000..a5874a5 --- /dev/null +++ b/crates/gvnic/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "gvnic" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" +description = "UEFI SimpleNetworkProtocol driver for the Google Virtual NIC (gVNIC / gve)" + +# Standalone workspace like ena/stage0: only builds for *-unknown-uefi, kept out of any +# parent workspace. Produces `gvnic.efi`, a resident UEFI boot-service driver that stage0 +# loads at runtime (GCP's UEFI firmware ships no gVNIC driver, and GCP requires gVNIC for +# Confidential VMs and Arm). build.rs forces the EFI_BOOT_SERVICE_DRIVER PE subsystem so +# the image stays resident. +[workspace] + +[dependencies] +uefi = { version = "0.35", features = ["alloc", "global_allocator", "panic_handler"] } +uefi-raw = "0.11" + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 +panic = "abort" diff --git a/crates/gvnic/build.rs b/crates/gvnic/build.rs new file mode 100644 index 0000000..9e1b3d5 --- /dev/null +++ b/crates/gvnic/build.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Force the PE subsystem to EFI Boot Service Driver (11) instead of the target's +//! default EFI Application (10). A UEFI *application* is unloaded the moment its +//! entry point returns, which would tear down our DriverBinding; a boot-service +//! driver stays resident. lld-link takes the last `/subsystem`, and this link-arg +//! is emitted after the target's, so it wins. Done here (not .cargo/config.toml) so +//! it travels with the crate regardless of where cargo is invoked. +fn main() { + println!("cargo::rustc-link-arg-bins=/subsystem:efi_boot_service_driver"); +} diff --git a/crates/gvnic/src/binding.rs b/crates/gvnic/src/binding.rs new file mode 100644 index 0000000..1ea9092 --- /dev/null +++ b/crates/gvnic/src/binding.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `EFI_DRIVER_BINDING_PROTOCOL` for gVNIC. `supported()` is the gate that keeps the +//! driver inert on non-GCP platforms: it returns `SUCCESS` only for PCI `1ae0:0042`. +//! `start()` brings the device up; `stop()` is stubbed (as in ena). + +use alloc::boxed::Box; + +use uefi::boot; +use uefi::{Handle, Status}; +use uefi_raw::protocol::device_path::DevicePathProtocol; +use uefi_raw::protocol::driver::DriverBindingProtocol; +use uefi_raw::Handle as RawHandle; + +use crate::device::{GVNIC_DEVICE_ID, GVNIC_VENDOR_ID}; +use crate::pci::PciIo; + +/// Build and install the DriverBinding on our own image handle. The instance must +/// outlive this function (the firmware keeps the pointer), so it is leaked. +pub fn install() -> uefi::Result<()> { + let image = boot::image_handle(); + let binding = Box::new(DriverBindingProtocol { + supported, + start, + stop, + version: 0x10, + image_handle: image.as_ptr(), + driver_binding_handle: image.as_ptr(), + }); + let ptr = Box::into_raw(binding); + unsafe { + boot::install_protocol_interface(Some(image), &DriverBindingProtocol::GUID, ptr.cast())?; + } + Ok(()) +} + +/// Return SUCCESS only for a gVNIC controller. Opens PciIo with GetProtocol (a +/// non-owning test open) and checks vendor + device id. +unsafe extern "efiapi" fn supported( + _this: *const DriverBindingProtocol, + controller_handle: RawHandle, + _remaining: *const DevicePathProtocol, +) -> Status { + let Some(controller) = (unsafe { Handle::from_ptr(controller_handle) }) else { + return Status::UNSUPPORTED; + }; + let params = boot::OpenProtocolParams { + handle: controller, + agent: boot::image_handle(), + controller: None, + }; + let pci = match unsafe { + boot::open_protocol::(params, boot::OpenProtocolAttributes::GetProtocol) + } { + Ok(p) => p, + Err(_) => return Status::UNSUPPORTED, + }; + // Gate on vendor AND device id: other Google virtual devices share vendor 0x1ae0. + match pci.vendor_device() { + Ok((GVNIC_VENDOR_ID, GVNIC_DEVICE_ID)) => Status::SUCCESS, + _ => Status::UNSUPPORTED, + } +} + +/// Bind the gVNIC controller: open PciIo BY_DRIVER (claiming the device), probe it +/// (reset + admin queue + describe/configure + QPLs + one TX/RX queue pair), then install +/// SNP on the handle. EDK2's MNP/IP4/TCP4/UDP4 binds on top, producing IP4_CONFIG2 for stage0. +unsafe extern "efiapi" fn start( + _this: *const DriverBindingProtocol, + controller_handle: RawHandle, + _remaining: *const DevicePathProtocol, +) -> Status { + let Some(controller) = (unsafe { Handle::from_ptr(controller_handle) }) else { + return Status::UNSUPPORTED; + }; + let params = boot::OpenProtocolParams { + handle: controller, + agent: boot::image_handle(), + controller: Some(controller), + }; + let pci = match unsafe { + boot::open_protocol::(params, boot::OpenProtocolAttributes::ByDriver) + } { + Ok(p) => p, + Err(e) => { + // ALREADY_STARTED is expected: connect_all_controllers reaches the NIC twice (via + // the parent bus and directly), so start() is invoked a second time once we + // already manage the device. That is benign; only log genuine failures. + if e.status() != Status::ALREADY_STARTED { + uefi::println!( + "gvnic: start(): open PciIo BY_DRIVER failed: {:?}", + e.status() + ); + } + return e.status(); + } + }; + uefi::println!("gvnic: start(): probing gVNIC device..."); + // On any error, `pci` drops here and closes the BY_DRIVER open (releasing the device). + let nic = match unsafe { crate::device::probe(&pci.0) } { + Ok(nic) => nic, + Err(e) => { + uefi::println!("gvnic: probe FAILED: {:?}", e); + return e; + } + }; + let mac = nic.mac(); + uefi::println!( + "gvnic: probe OK mac={:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x} mtu={}", + mac[0], + mac[1], + mac[2], + mac[3], + mac[4], + mac[5], + nic.mtu + ); + // Keep PciIo open for the device's lifetime (probe stored the raw pointer in `nic`). + core::mem::forget(pci); + match crate::snp::install(controller, nic) { + Ok(()) => { + uefi::println!("gvnic: SNP installed on controller; networking should come up"); + Status::SUCCESS + } + Err(e) => { + uefi::println!("gvnic: SNP install failed: {:?}", e.status()); + e.status() + } + } +} + +/// Unbind: shutdown queues, uninstall SNP, free DMA, close PciIo. Stubbed. +unsafe extern "efiapi" fn stop( + _this: *const DriverBindingProtocol, + _controller_handle: RawHandle, + _number_of_children: usize, + _child_handle_buffer: *const RawHandle, +) -> Status { + Status::UNSUPPORTED +} diff --git a/crates/gvnic/src/device.rs b/crates/gvnic/src/device.rs new file mode 100644 index 0000000..e14e8a0 --- /dev/null +++ b/crates/gvnic/src/device.rs @@ -0,0 +1,921 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Device protocol derived from the Linux `gve` driver (drivers/net/ethernet/google/gve), +// Copyright (C) 2015-2024 Google LLC, licensed `(GPL-2.0 OR MIT)`; used here under the MIT +// terms. Reference: torvalds/linux @ 45e0a63f9c86. Section numbers (`spec §N`) refer to the +// extracted protocol notes for that tree; `gve_*.{c,h}:line` cite the reference directly. + +//! gVNIC hardware layer: the bare minimum to push and poll Ethernet frames, enough for +//! EDK2's IP4/TCP4 stack to netboot over it. +//! +//! Queue format GQI_QPL ("registered pages"), ONE TX + ONE RX queue, polled (no +//! interrupts), no offloads, no RSS. Everything device-facing is BIG-endian: BAR0 +//! registers, admin-queue commands, descriptors, doorbells, event counters. +//! +//! Flow (probe): PCI enable -> version string -> register admin queue (by PCI revision) -> +//! VERIFY_DRIVER_COMPATIBILITY -> DESCRIBE_DEVICE (+ option TLVs) -> +//! CONFIGURE_DEVICE_RESOURCES -> allocate rings + QPLs -> REGISTER_PAGE_LIST (TX, RX) -> +//! CREATE_TX_QUEUE -> CREATE_RX_QUEUE -> RX doorbell -> link poll -> ExitBootServices hook. +//! +//! Data path: TX copies each frame into a fixed 2 KiB slot of the TX QPL and posts ONE +//! packet descriptor (seg_addr = QPL byte offset); completions come from the TX event +//! counter. RX buffers are QPL pages (slot i = page i, never flipped); a descriptor is +//! ready when its 3-bit seqno matches the expected one (1..7); the frame starts 2 bytes in. +//! +//! All DMA memory is `PciIo.AllocateBuffer` + `Map(CommonBuffer)`, so it is also correct +//! under memory encryption (SEV), where it must be shared with the host. + +// Several fields exist only to keep device-visible buffers alive (never read back), and a +// few protocol constants are kept for reference. +#![allow(dead_code)] + +use alloc::boxed::Box; +use alloc::vec; +use alloc::vec::Vec; +use core::ffi::c_void; +use core::ptr::NonNull; +use core::sync::atomic::{fence, Ordering}; + +use uefi::boot::{self, EventType, Tpl}; +use uefi::{Event, Status}; + +use crate::pci::{PciAttrOp, PciIoProtocol, PciMapOp, PciWidth, PCI_ATTR_BUS_MASTER}; + +/// `uefi::println!` with a `gvnic:` prefix. +macro_rules! log { + ($($a:tt)*) => { uefi::println!("gvnic: {}", format_args!($($a)*)) }; +} + +/// PCI identity (gve.h:26,29: PCI_VENDOR_ID_GOOGLE / PCI_DEV_ID_GVNIC). +pub const GVNIC_VENDOR_ID: u16 = 0x1ae0; +pub const GVNIC_DEVICE_ID: u16 = 0x0042; + +/// BAR0 = register block, BAR2 = doorbells (array of BE32, index i at byte 4*i). +const REG_BAR: u8 = 0; +const DB_BAR: u8 = 2; + +/// `struct gve_registers` offsets (gve_register.h:11-24). +mod regs { + pub const DEVICE_STATUS: u64 = 0x00; + pub const DRIVER_STATUS: u64 = 0x04; + pub const MAX_TX_QUEUES: u64 = 0x08; + pub const MAX_RX_QUEUES: u64 = 0x0c; + pub const ADMINQ_PFN: u64 = 0x10; + pub const ADMINQ_DOORBELL: u64 = 0x14; + pub const ADMINQ_EVENT_COUNTER: u64 = 0x18; + pub const DRIVER_VERSION: u64 = 0x1f; + pub const ADMINQ_BASE_HI: u64 = 0x20; + pub const ADMINQ_BASE_LO: u64 = 0x24; + pub const ADMINQ_LENGTH: u64 = 0x28; +} + +/// device_status bits (gve_register.h:26-31). +const DEV_STS_RESET_REQUESTED: u32 = 1 << 1; +const DEV_STS_LINK_UP: u32 = 1 << 2; +const DEV_STS_IS_RESET: u32 = 1 << 4; +/// driver_status bits (gve_register.h:33-36). +const DRV_STS_RUN: u32 = 1 << 0; +const DRV_STS_RESET: u32 = 1 << 1; + +/// Admin opcodes (gve_adminq.h:13-35). +const OP_DESCRIBE_DEVICE: u32 = 0x1; +const OP_CONFIGURE_DEVICE_RESOURCES: u32 = 0x2; +const OP_REGISTER_PAGE_LIST: u32 = 0x3; +const OP_CREATE_TX_QUEUE: u32 = 0x5; +const OP_CREATE_RX_QUEUE: u32 = 0x6; +const OP_VERIFY_DRIVER_COMPATIBILITY: u32 = 0xf; + +/// Admin status codes (gve_adminq.h:47-66). +const AQ_PASSED: u32 = 0x0000_0001; +const AQ_UNIMPLEMENTED: u32 = 0xffff_fffe; + +/// Device-option ids (gve_adminq.h:192-204). +const OPT_GQI_RAW_ADDRESSING: u16 = 0x1; +const OPT_GQI_RDA: u16 = 0x2; +const OPT_GQI_QPL: u16 = 0x3; +const OPT_DQO_RDA: u16 = 0x4; +const OPT_DQO_QPL: u16 = 0x7; +const OPT_JUMBO_FRAMES: u16 = 0x8; +/// GVE_SUP_JUMBO_FRAMES_MASK (gve_adminq.h:222). +const SUP_JUMBO_FRAMES: u32 = 1 << 2; + +/// CONFIGURE_DEVICE_RESOURCES queue_format (gve.h:749-755). +const QUEUE_FORMAT_GQI_QPL: u8 = 2; +/// VERIFY_DRIVER_COMPATIBILITY capability bit 0 = gqi_qpl (gve_adminq.h:233-258). +const DRIVER_CAP_GQI_QPL: u64 = 1 << 0; +const DRIVER_INFO_LEN: usize = 304; // sizeof(struct gve_driver_info) + +/// Version string, written byte-by-byte to DRIVER_VERSION (gve_main.c:32-40, 2631-2646). +const VERSION_STRING: &[u8] = b"GVE-1.0.0\n"; + +/// Polling limits (gve_adminq.c:15-17): 20 ms steps; 100 for a command, 500 for a release. +const SLEEP_MS: usize = 20; +const CMD_CHECKS: usize = 100; +const RELEASE_CHECKS: usize = 500; +const LINK_CHECKS: usize = 250; // 5 s (Linux does not wait; we log the outcome) + +const PAGE: usize = 4096; +const AQ_SLOTS: u32 = (PAGE / 64) as u32; // 64 slots of 64 bytes +const BUF: usize = 2048; // RX packet_buffer_size and TX slot size (gve.h:62) +const RX_PAD: usize = 2; // GVE_RX_PAD (gve_desc.h:79-82) +const ETH_HLEN: usize = 14; +/// Largest MTU whose frame (+ RX pad) fits one 2 KiB buffer: keeps RX single-fragment and +/// TX single-descriptor (spec §9). +const MTU_CAP: u32 = (BUF - ETH_HLEN - RX_PAD) as u32; +const MTU_MIN: u32 = 68; + +/// RX descriptor flags_seq (host order after BE16 decode; gve_desc.h:109-119). +const RXF_ERR: u16 = 1 << (3 + 8); +const RXF_PKT_CONT: u16 = 1 << (3 + 10); + +const EFI_BOOT_SERVICES_DATA: u32 = 4; +const EFI_ALLOCATE_ANY_PAGES: u32 = 0; +/// EFI_PCI_IO_ATTRIBUTE_MEMORY. +const PCI_ATTR_MEMORY: u64 = 0x0200; + +fn delay_ms(ms: usize) { + boot::stall(ms * 1000); +} + +// ---- big-endian field access in DMA memory (byte-wise, volatile) --------------- + +unsafe fn put_be16(p: *mut u8, off: usize, v: u16) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn put_be32(p: *mut u8, off: usize, v: u32) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn put_be64(p: *mut u8, off: usize, v: u64) { + for (i, b) in v.to_be_bytes().iter().enumerate() { + p.add(off + i).write_volatile(*b); + } +} +unsafe fn get_be16(p: *const u8, off: usize) -> u16 { + u16::from_be_bytes([p.add(off).read_volatile(), p.add(off + 1).read_volatile()]) +} +unsafe fn get_be32(p: *const u8, off: usize) -> u32 { + let mut b = [0u8; 4]; + for (i, x) in b.iter_mut().enumerate() { + *x = p.add(off + i).read_volatile(); + } + u32::from_be_bytes(b) +} +unsafe fn get_be64(p: *const u8, off: usize) -> u64 { + let mut b = [0u8; 8]; + for (i, x) in b.iter_mut().enumerate() { + *x = p.add(off + i).read_volatile(); + } + u64::from_be_bytes(b) +} + +// Command buffers are plain [u8; 64] built on the stack, then copied into the AQ slot. +fn cmd_new(opcode: u32) -> [u8; 64] { + let mut c = [0u8; 64]; + c[0..4].copy_from_slice(&opcode.to_be_bytes()); + c +} +fn cmd_u8(c: &mut [u8; 64], off: usize, v: u8) { + c[off] = v; +} +fn cmd_be16(c: &mut [u8; 64], off: usize, v: u16) { + c[off..off + 2].copy_from_slice(&v.to_be_bytes()); +} +fn cmd_be32(c: &mut [u8; 64], off: usize, v: u32) { + c[off..off + 4].copy_from_slice(&v.to_be_bytes()); +} +fn cmd_be64(c: &mut [u8; 64], off: usize, v: u64) { + c[off..off + 8].copy_from_slice(&v.to_be_bytes()); +} + +// ---- MMIO (BAR0 registers, BAR2 doorbells) via PciIo.Mem; device is big-endian --- + +unsafe fn mmio_read32(pci: &PciIoProtocol, bar: u8, off: u64) -> u32 { + let mut v: u32 = 0; + let st = (pci.mem.read)(pci, PciWidth::U32, bar, off, 1, (&mut v as *mut u32).cast()); + if !st.is_success() { + log!(" MMIO read bar{bar}@0x{off:02x} failed: {st:?}"); + } + u32::from_be(v) +} +unsafe fn mmio_write32(pci: &PciIoProtocol, bar: u8, off: u64, val: u32) { + let mut v = val.to_be(); + let st = (pci.mem.write)(pci, PciWidth::U32, bar, off, 1, (&mut v as *mut u32).cast()); + if !st.is_success() { + log!(" MMIO write bar{bar}@0x{off:02x} failed: {st:?}"); + } +} +unsafe fn mmio_write16(pci: &PciIoProtocol, bar: u8, off: u64, val: u16) { + let mut v = val.to_be(); + let st = (pci.mem.write)(pci, PciWidth::U16, bar, off, 1, (&mut v as *mut u16).cast()); + if !st.is_success() { + log!(" MMIO write16 bar{bar}@0x{off:02x} failed: {st:?}"); + } +} +unsafe fn mmio_write8(pci: &PciIoProtocol, bar: u8, off: u64, val: u8) { + let mut v = val; + let _ = (pci.mem.write)(pci, PciWidth::U8, bar, off, 1, (&mut v as *mut u8).cast()); +} +unsafe fn reg_rd(pci: &PciIoProtocol, off: u64) -> u32 { + mmio_read32(pci, REG_BAR, off) +} +unsafe fn reg_wr(pci: &PciIoProtocol, off: u64, v: u32) { + mmio_write32(pci, REG_BAR, off, v) +} +/// Ring doorbell `db_index` (BAR2 + 4*db_index) with a free-running count. Release fence +/// first, so every descriptor/payload store is visible before the device is told. +unsafe fn doorbell(pci: &PciIoProtocol, db_index: u32, value: u32) { + fence(Ordering::Release); + mmio_write32(pci, DB_BAR, 4 * db_index as u64, value); +} + +unsafe fn cfg_r8(pci: &PciIoProtocol, off: u32) -> u8 { + let mut v: u8 = 0; + let _ = (pci.pci.read)(pci, PciWidth::U8, off, 1, (&mut v as *mut u8).cast()); + v +} +unsafe fn cfg_r16(pci: &PciIoProtocol, off: u32) -> u16 { + let mut v: u16 = 0; + let _ = (pci.pci.read)(pci, PciWidth::U16, off, 1, (&mut v as *mut u16).cast()); + v +} +unsafe fn cfg_w16(pci: &PciIoProtocol, off: u32, val: u16) { + let mut v = val; + let _ = (pci.pci.write)(pci, PciWidth::U16, off, 1, (&mut v as *mut u16).cast()); +} + +/// MSI-X table size (Message Control bits[10:0] + 1), or 0 if there is no MSI-X capability. +/// Read only: MSI-X stays DISABLED (we poll); the count sizes the notification blocks the +/// device expects in CONFIGURE_DEVICE_RESOURCES, exactly as Linux computes it. +unsafe fn msix_table_size(pci: &PciIoProtocol) -> u32 { + let mut off = (cfg_r8(pci, 0x34) & 0xfc) as u32; // capabilities pointer + let mut guard = 0; + while off != 0 && guard < 48 { + if cfg_r8(pci, off) == 0x11 { + return (cfg_r16(pci, off + 2) & 0x7ff) as u32 + 1; + } + off = (cfg_r8(pci, off + 1) & 0xfc) as u32; + guard += 1; + } + 0 +} + +// ---- DMA (common buffer via PciIo) ------------------------------------------------- + +/// A coherent DMA region: host pointer + device bus address. Never freed (the device owns +/// it for the controller's lifetime; after a reset nothing references it). +struct Dma { + host: *mut u8, + dev: u64, + mapping: *mut c_void, + pages: usize, +} + +impl Dma { + /// Allocate `bytes` (rounded up to pages), zeroed, mapped as ONE contiguous bus-master + /// common buffer (QPLs rely on page i being at `dev + i*4096`). + unsafe fn alloc(pci: &PciIoProtocol, bytes: usize) -> Result { + let pages = bytes.div_ceil(PAGE).max(1); + let mut host: *mut c_void = core::ptr::null_mut(); + let st = (pci.allocate_buffer)( + pci, + EFI_ALLOCATE_ANY_PAGES, + EFI_BOOT_SERVICES_DATA, + pages, + &mut host, + 0, + ); + if !st.is_success() || host.is_null() { + log!(" AllocateBuffer({pages} pages) failed: {st:?}"); + return Err(if st.is_success() { + Status::OUT_OF_RESOURCES + } else { + st + }); + } + core::ptr::write_bytes(host as *mut u8, 0, pages * PAGE); + let want = pages * PAGE; + let mut nbytes = want; + let mut dev: u64 = 0; + let mut mapping: *mut c_void = core::ptr::null_mut(); + let st = (pci.map)( + pci, + PciMapOp::CommonBuffer, + host as *const c_void, + &mut nbytes, + &mut dev, + &mut mapping, + ); + if !st.is_success() || nbytes != want { + log!(" Map({want} bytes) failed: {st:?} (mapped {nbytes})"); + let _ = (pci.free_buffer)(pci, pages, host); + return Err(if st.is_success() { + Status::OUT_OF_RESOURCES + } else { + st + }); + } + Ok(Dma { + host: host as *mut u8, + dev, + mapping, + pages, + }) + } +} + +// ---- Admin queue (spec §3) ------------------------------------------------------------- + +struct AdminQueue { + dma: Dma, + /// Free-running producer count; the device's event counter must equal it when idle. + prod: u32, +} + +impl AdminQueue { + /// Submit one 64-byte command and wait for it; returns the device status word. + unsafe fn exec_status(&mut self, pci: &PciIoProtocol, cmd: &[u8; 64]) -> Result { + let tail = reg_rd(pci, regs::ADMINQ_EVENT_COUNTER); + if tail != self.prod { + log!(" AQ out of sync: event_counter={tail} prod={}", self.prod); + return Err(Status::DEVICE_ERROR); + } + let slot = self.dma.host.add(((self.prod % AQ_SLOTS) * 64) as usize); + for (i, b) in cmd.iter().enumerate() { + slot.add(i).write_volatile(*b); + } + self.prod = self.prod.wrapping_add(1); + fence(Ordering::Release); + reg_wr(pci, regs::ADMINQ_DOORBELL, self.prod); + let mut done = false; + for _ in 0..CMD_CHECKS { + if reg_rd(pci, regs::ADMINQ_EVENT_COUNTER) == self.prod { + done = true; + break; + } + delay_ms(SLEEP_MS); + } + let opcode = u32::from_be_bytes([cmd[0], cmd[1], cmd[2], cmd[3]]); + if !done { + log!(" AQ opcode 0x{opcode:x}: timed out"); + return Err(Status::TIMEOUT); + } + fence(Ordering::Acquire); + Ok(get_be32(slot, 4)) + } + + /// Submit one command; anything but PASSED is an error (logged with the opcode). + unsafe fn exec(&mut self, pci: &PciIoProtocol, cmd: &[u8; 64]) -> Result<(), Status> { + let st = self.exec_status(pci, cmd)?; + let opcode = u32::from_be_bytes([cmd[0], cmd[1], cmd[2], cmd[3]]); + if st == AQ_PASSED { + log!(" AQ opcode 0x{opcode:x}: PASSED"); + Ok(()) + } else { + log!(" AQ opcode 0x{opcode:x}: status 0x{st:08x}"); + Err(Status::DEVICE_ERROR) + } + } +} + +/// Register the admin queue (spec §3.2; gve_adminq.c:341-354): PFN on rev 0, else +/// length + base hi/lo + RUN. +unsafe fn register_adminq(pci: &PciIoProtocol, rev: u8, aq: &Dma) { + if rev < 1 { + reg_wr(pci, regs::ADMINQ_PFN, (aq.dev / PAGE as u64) as u32); + } else { + mmio_write16(pci, REG_BAR, regs::ADMINQ_LENGTH, PAGE as u16); + reg_wr(pci, regs::ADMINQ_BASE_HI, (aq.dev >> 32) as u32); + reg_wr(pci, regs::ADMINQ_BASE_LO, aq.dev as u32); + reg_wr(pci, regs::DRIVER_STATUS, DRV_STS_RUN); + } +} + +/// Reset handshake = release the admin queue (spec §2.4; gve_adminq.c:368-397). The only +/// guarantee the device has stopped DMA. Bounded (500 x 20 ms); returns whether it completed. +unsafe fn reset(pci: &PciIoProtocol, rev: u8) -> bool { + if rev < 1 { + reg_wr(pci, regs::ADMINQ_PFN, 0); + for _ in 0..RELEASE_CHECKS { + if reg_rd(pci, regs::ADMINQ_PFN) == 0 { + return true; + } + delay_ms(SLEEP_MS); + } + } else { + reg_wr(pci, regs::DRIVER_STATUS, DRV_STS_RESET); + for _ in 0..RELEASE_CHECKS { + if reg_rd(pci, regs::DEVICE_STATUS) & DEV_STS_IS_RESET != 0 { + return true; + } + delay_ms(SLEEP_MS); + } + } + false +} + +// ---- ExitBootServices: stop DMA before the OS owns the memory --------------------------- + +struct EbsCtx { + pci: *const PciIoProtocol, + rev: u8, +} + +/// Reset the device at ExitBootServices (spec §10.3): RX buffers are posted into +/// boot-services memory the OS is about to reuse. No logging here (console may be gone). +unsafe extern "efiapi" fn on_exit_boot_services(_e: Event, ctx: Option>) { + if let Some(c) = ctx { + let c = &*(c.as_ptr() as *const EbsCtx); + let _ = reset(&*c.pci, c.rev); + } +} + +// ---- Device description (spec §4.2) ----------------------------------------------------- + +struct Desc { + max_registered_pages: u64, + tx_entries: u32, + rx_entries: u32, + mtu: u32, + counters: u32, + tx_pages_per_qpl: u32, + mac: [u8; 6], +} + +/// Parse the device descriptor + option TLVs; log everything (first-boot visibility); pick +/// GQI_QPL (present, or no format option at all = Linux's default) or fail. +unsafe fn parse_describe(buf: *const u8) -> Result { + let mut d = Desc { + max_registered_pages: get_be64(buf, 0), + tx_entries: get_be16(buf, 10) as u32, + rx_entries: get_be16(buf, 12) as u32, + mtu: get_be16(buf, 16) as u32, + counters: get_be16(buf, 18) as u32, + tx_pages_per_qpl: get_be16(buf, 20) as u32, + mac: [0; 6], + }; + for (i, m) in d.mac.iter_mut().enumerate() { + *m = buf.add(24 + i).read_volatile(); + } + let num_opts = get_be16(buf, 30) as usize; + let total_len = (get_be16(buf, 32) as usize).clamp(40, PAGE); + log!( + " describe: max_reg_pages={} tx_entries={} rx_entries={} default_queues={} mtu={} counters={} tx_pages_per_qpl={} rx_pages_per_qpl={} options={} total_len={}", + d.max_registered_pages, d.tx_entries, d.rx_entries, get_be16(buf, 14), d.mtu, + d.counters, d.tx_pages_per_qpl, get_be16(buf, 22), num_opts, total_len + ); + + let mut off = 40usize; + let mut gqi_qpl_mask: Option = None; + let mut other_formats: Vec = Vec::new(); + let mut jumbo_mtu: Option = None; + for _ in 0..num_opts { + if off + 8 > total_len { + log!(" describe: option header runs past total_length"); + return Err(Status::DEVICE_ERROR); + } + let id = get_be16(buf, off); + let len = get_be16(buf, off + 2) as usize; + let req = get_be32(buf, off + 4); + let p = off + 8; + if p + len > total_len { + log!(" describe: option 0x{id:x} runs past total_length"); + return Err(Status::DEVICE_ERROR); + } + let mask = if len >= 4 { get_be32(buf, p) } else { 0 }; + log!(" option 0x{id:x} len={len} required_features=0x{req:x} mask=0x{mask:x}"); + if req == 0 { + match id { + OPT_GQI_QPL if len >= 4 => gqi_qpl_mask = Some(mask), + OPT_JUMBO_FRAMES if len >= 6 => jumbo_mtu = Some(get_be16(buf, p + 4) as u32), + OPT_GQI_RAW_ADDRESSING | OPT_GQI_RDA | OPT_DQO_RDA | OPT_DQO_QPL => { + other_formats.push(id) + } + _ => {} + } + } + off = p + len; + } + + // Queue format: GQI_QPL if offered, or if no format option is present at all (Linux's + // default, gve_adminq.c:1158-1165). Otherwise this device needs a mode we don't drive. + let mask = match gqi_qpl_mask { + Some(m) => m, + None if other_formats.is_empty() => 0, + None => { + log!(" describe: GQI_QPL not offered (formats offered: {other_formats:x?})"); + return Err(Status::UNSUPPORTED); + } + }; + if !other_formats.is_empty() { + log!(" describe: also offered {other_formats:x?}; using GQI_QPL"); + } + if let (Some(j), true) = (jumbo_mtu, mask & SUP_JUMBO_FRAMES != 0) { + d.mtu = j; + } + Ok(d) +} + +// ---- Queues ----------------------------------------------------------------------------- + +struct Tx { + ring: Dma, // entries * 16 B packet descriptors + qpl: Dma, // tx_pages_per_qpl pages, carved into BUF-sized slots + entries: u32, + slots: u32, + req: u32, // free-running: descriptors posted + done: u32, // free-running: descriptors reaped + db_index: u32, + counter: *const u8, // &counter_array[counter_index] + callers: Vec<*const c_void>, +} + +struct Rx { + desc: Dma, // entries * 64 B, device-written + data: Dma, // entries * 8 B: BE64 QPL offset per slot (= i * 4096, never changed) + qpl: Dma, // entries pages, one buffer per page at offset 0 + entries: u32, + cnt: u32, // free-running: descriptors consumed + fill: u32, // free-running: slots posted + seq: u16, // expected seqno, 1..7 + db_index: u32, + skip_cont: bool, // dropping the rest of a multi-fragment packet +} + +/// A bound gVNIC: one TX + one RX GQI-QPL queue, polled. +pub struct Gvnic { + pci: *const PciIoProtocol, + /// Device MTU (L3 payload; GCP default 1460), capped so a frame fits one 2 KiB buffer. + pub mtu: u32, + mac: [u8; 6], + rev: u8, + aq: AdminQueue, + counters: Dma, + irq_dbs: Dma, + qres: Dma, + tx: Tx, + rx: Rx, +} + +impl Gvnic { + pub fn mac(&self) -> [u8; 6] { + self.mac + } + + /// RX is fully posted at probe (the data ring must be prefilled before CREATE_RX_QUEUE, + /// spec §4.7), so SNP Initialize has nothing to do here. + pub unsafe fn init_rx(&mut self) {} + + /// Copy one received frame into `out` (capacity `cap`); `None` if nothing is pending. + /// Errored, multi-fragment, or oversized frames are consumed and dropped. + pub unsafe fn receive(&mut self, out: *mut u8, cap: usize) -> Option { + let pci = &*self.pci; + let rx = &mut self.rx; + loop { + let idx = (rx.cnt % rx.entries) as usize; + let d = rx.desc.host.add(idx * 64); + let flags_seq = get_be16(d, 62); + if flags_seq & 0x7 != rx.seq { + return None; + } + fence(Ordering::Acquire); + let len = get_be16(d, 60) as usize; + let cont = flags_seq & RXF_PKT_CONT != 0; + let mut got = None; + if rx.skip_cont { + rx.skip_cont = cont; // drop through the last fragment + } else if flags_seq & RXF_ERR != 0 || cont || !(RX_PAD..=BUF).contains(&len) { + rx.skip_cont = cont; + } else { + let n = len - RX_PAD; + if n <= cap { + let src = rx.qpl.host.add(idx * PAGE + RX_PAD); + core::ptr::copy_nonoverlapping(src, out, n); + got = Some(n); + } + } + // Hand the slot back only after its data was copied out (spec §7.5). + rx.cnt = rx.cnt.wrapping_add(1); + rx.seq = if rx.seq == 7 { 1 } else { rx.seq + 1 }; + rx.fill = rx.fill.wrapping_add(1); + doorbell(pci, rx.db_index, rx.fill); + if got.is_some() { + return got; + } + } + } + + /// Queue one complete Ethernet frame. `caller` is the SNP buffer, handed back by + /// `poll_tx()` once the device has consumed the descriptor. + pub unsafe fn transmit( + &mut self, + data: *const u8, + len: usize, + caller: *const c_void, + ) -> Result<(), Status> { + let pci = &*self.pci; + let tx = &mut self.tx; + if len == 0 || len > self.mtu as usize + ETH_HLEN { + return Err(Status::INVALID_PARAMETER); + } + let in_flight = tx.req.wrapping_sub(tx.done); + if in_flight >= tx.entries.min(tx.slots) { + return Err(Status::NOT_READY); + } + let slot = (tx.req % tx.slots) as usize; + let qpl_off = slot * BUF; + core::ptr::copy_nonoverlapping(data, tx.qpl.host.add(qpl_off), len); + // gve_tx_pkt_desc (gve_desc.h:26-34): type_flags=STD(0), offsets 0, desc_cnt=1, + // len = seg_len = frame length, seg_addr = QPL byte offset. + let d = tx.ring.host.add(((tx.req % tx.entries) * 16) as usize); + d.write_volatile(0); + d.add(1).write_volatile(0); + d.add(2).write_volatile(0); + d.add(3).write_volatile(1); + put_be16(d, 4, len as u16); + put_be16(d, 6, len as u16); + put_be64(d, 8, qpl_off as u64); + tx.callers[slot] = caller; + tx.req = tx.req.wrapping_add(1); + doorbell(pci, tx.db_index, tx.req); + Ok(()) + } + + /// Reap one completed TX: the caller's buffer pointer, or `None`. + pub unsafe fn poll_tx(&mut self) -> Option<*const c_void> { + let tx = &mut self.tx; + let nic_done = get_be32(tx.counter, 0); + fence(Ordering::Acquire); + let completed = nic_done.wrapping_sub(tx.done); + let in_flight = tx.req.wrapping_sub(tx.done); + if completed == 0 || completed > in_flight { + return None; + } + let slot = (tx.done % tx.slots) as usize; + tx.done = tx.done.wrapping_add(1); + Some(tx.callers[slot]) + } +} + +/// Bring the device up (spec §10.1). On failure after the admin queue is registered the +/// device is reset, so nothing is left doing DMA. +pub unsafe fn probe(pci: &PciIoProtocol) -> Result { + let rev = cfg_r8(pci, 0x08); + log!("PCI 1ae0:0042 revision {rev}"); + + // Memory decode + bus mastering; INTx disabled (Command bit 10). MSI-X left disabled. + let st = (pci.attributes)( + pci, + PciAttrOp::Enable, + PCI_ATTR_MEMORY | PCI_ATTR_BUS_MASTER, + core::ptr::null_mut(), + ); + log!("memory+bus-master enable: {st:?}"); + cfg_w16(pci, 0x04, cfg_r16(pci, 0x04) | (1 << 10)); + + let num_msix = msix_table_size(pci); + if num_msix < 3 { + log!("MSI-X table size {num_msix} < 3 (GVE_MIN_MSIX)"); + return Err(Status::UNSUPPORTED); + } + let num_ntfy = (num_msix - 1) & !1; + let max_tx = reg_rd(pci, regs::MAX_TX_QUEUES); + let max_rx = reg_rd(pci, regs::MAX_RX_QUEUES); + let dev_status = reg_rd(pci, regs::DEVICE_STATUS); + log!("msix={num_msix} ntfy_blks={num_ntfy} max_tx={max_tx} max_rx={max_rx} device_status=0x{dev_status:x}"); + if max_tx == 0 || max_rx == 0 { + return Err(Status::DEVICE_ERROR); + } + + for b in VERSION_STRING { + mmio_write8(pci, REG_BAR, regs::DRIVER_VERSION, *b); + } + + let aq_dma = Dma::alloc(pci, PAGE)?; + register_adminq(pci, rev, &aq_dma); + let ec = reg_rd(pci, regs::ADMINQ_EVENT_COUNTER); + if ec != 0 { + log!("event_counter={ec} after AQ registration (expected 0)"); + } + let aq = AdminQueue { + dma: aq_dma, + prod: ec, + }; + + match bring_up(pci, rev, num_ntfy, max_tx, aq) { + Ok(nic) => Ok(nic), + Err(e) => { + let ok = reset(pci, rev); + log!( + "bring-up failed ({e:?}); device reset {}", + if ok { "OK" } else { "TIMED OUT" } + ); + Err(e) + } + } +} + +/// Steps 7-19 of the bring-up checklist; the admin queue moves into the returned device. +unsafe fn bring_up( + pci: &PciIoProtocol, + rev: u8, + num_ntfy: u32, + max_tx: u32, + mut aq: AdminQueue, +) -> Result { + // VERIFY_DRIVER_COMPATIBILITY (spec §4.1): PASSED or UNIMPLEMENTED both fine. + let info = Dma::alloc(pci, DRIVER_INFO_LEN)?; + info.host.write_volatile(1); // os_type: 1 (the only value defined) + put_be64(info.host, 16, DRIVER_CAP_GQI_QPL); + for (i, b) in b"lockboot-gvnic".iter().enumerate() { + info.host.add(48 + i).write_volatile(*b); + info.host.add(176 + i).write_volatile(*b); + } + let mut c = cmd_new(OP_VERIFY_DRIVER_COMPATIBILITY); + cmd_be64(&mut c, 8, DRIVER_INFO_LEN as u64); + cmd_be64(&mut c, 16, info.dev); + match aq.exec_status(pci, &c)? { + AQ_PASSED => log!(" verify-driver-compatibility: PASSED"), + AQ_UNIMPLEMENTED => log!(" verify-driver-compatibility: UNIMPLEMENTED (ok)"), + s => { + log!(" verify-driver-compatibility: status 0x{s:08x}"); + return Err(Status::DEVICE_ERROR); + } + } + + // DESCRIBE_DEVICE (spec §4.2). + let desc_buf = Dma::alloc(pci, PAGE)?; + let mut c = cmd_new(OP_DESCRIBE_DEVICE); + cmd_be64(&mut c, 8, desc_buf.dev); + cmd_be32(&mut c, 16, 1); // descriptor version + cmd_be32(&mut c, 20, PAGE as u32); // available length + aq.exec(pci, &c)?; + let d = parse_describe(desc_buf.host)?; + + let pow2 = |n: u32| n != 0 && n.is_power_of_two(); + if !pow2(d.tx_entries) || !pow2(d.rx_entries) || d.counters == 0 || d.tx_pages_per_qpl == 0 { + log!(" describe: unusable ring/counter geometry"); + return Err(Status::DEVICE_ERROR); + } + let pages_needed = d.tx_pages_per_qpl as u64 + d.rx_entries as u64; + if pages_needed > d.max_registered_pages { + log!(" describe: need {pages_needed} QPL pages > max_registered_pages"); + return Err(Status::DEVICE_ERROR); + } + if d.mtu < MTU_MIN { + log!(" describe: mtu {} < {MTU_MIN}", d.mtu); + return Err(Status::DEVICE_ERROR); + } + let mtu = d.mtu.min(MTU_CAP); + + // CONFIGURE_DEVICE_RESOURCES (spec §4.3): counter array + irq-doorbell index array. + let counters = Dma::alloc(pci, d.counters as usize * 4)?; + let irq_dbs = Dma::alloc(pci, num_ntfy as usize * 64)?; + let mut c = cmd_new(OP_CONFIGURE_DEVICE_RESOURCES); + cmd_be64(&mut c, 8, counters.dev); + cmd_be64(&mut c, 16, irq_dbs.dev); + cmd_be32(&mut c, 24, d.counters); + cmd_be32(&mut c, 28, num_ntfy); + cmd_be32(&mut c, 32, 64); // irq_db_stride + cmd_be32(&mut c, 36, 0); // ntfy_blk_msix_base_idx + cmd_u8(&mut c, 40, QUEUE_FORMAT_GQI_QPL); + aq.exec(pci, &c)?; + + // Rings + QPLs. Queue resources: one page, TX at 0, RX at 64. + let qres = Dma::alloc(pci, PAGE)?; + let tx_ring = Dma::alloc(pci, d.tx_entries as usize * 16)?; + let tx_qpl = Dma::alloc(pci, d.tx_pages_per_qpl as usize * PAGE)?; + let rx_desc = Dma::alloc(pci, d.rx_entries as usize * 64)?; + let rx_data = Dma::alloc(pci, d.rx_entries as usize * 8)?; + let rx_qpl = Dma::alloc(pci, d.rx_entries as usize * PAGE)?; + for i in 0..d.rx_entries as usize { + put_be64(rx_data.host, i * 8, (i * PAGE) as u64); + } + + // REGISTER_PAGE_LIST (spec §4.5): TX id 0, RX id min(max_tx, ntfy/2) (Linux's values). + let tx_qpl_id = 0u32; + let rx_qpl_id = max_tx.min(num_ntfy / 2); + for (id, qpl, pages) in [ + (tx_qpl_id, &tx_qpl, d.tx_pages_per_qpl), + (rx_qpl_id, &rx_qpl, d.rx_entries), + ] { + let list = Dma::alloc(pci, pages as usize * 8)?; + for i in 0..pages as usize { + put_be64(list.host, i * 8, qpl.dev + (i * PAGE) as u64); + } + let mut c = cmd_new(OP_REGISTER_PAGE_LIST); + cmd_be32(&mut c, 8, id); + cmd_be32(&mut c, 12, pages); + cmd_be64(&mut c, 16, list.dev); + cmd_be64(&mut c, 24, PAGE as u64); + aq.exec(pci, &c)?; + } + + // CREATE_TX_QUEUE (spec §4.6). + let mut c = cmd_new(OP_CREATE_TX_QUEUE); + cmd_be32(&mut c, 8, 0); // queue_id + cmd_be64(&mut c, 16, qres.dev); + cmd_be64(&mut c, 24, tx_ring.dev); + cmd_be32(&mut c, 32, tx_qpl_id); + cmd_be32(&mut c, 36, 0); // ntfy_id + cmd_be16(&mut c, 48, d.tx_entries as u16); + aq.exec(pci, &c)?; + let tx_db = get_be32(qres.host, 0); + let tx_ctr = get_be32(qres.host, 4); + + // CREATE_RX_QUEUE (spec §4.7). Data ring is already prefilled. + let mut c = cmd_new(OP_CREATE_RX_QUEUE); + cmd_be32(&mut c, 8, 0); // queue_id + cmd_be32(&mut c, 12, 0); // index + cmd_be32(&mut c, 20, num_ntfy / 2); // ntfy_id + cmd_be64(&mut c, 24, qres.dev + 64); + cmd_be64(&mut c, 32, rx_desc.dev); + cmd_be64(&mut c, 40, rx_data.dev); + cmd_be32(&mut c, 48, rx_qpl_id); + cmd_be16(&mut c, 52, d.rx_entries as u16); + cmd_be16(&mut c, 54, BUF as u16); // packet_buffer_size + aq.exec(pci, &c)?; + let rx_db = get_be32(qres.host, 64); + log!(" queues: tx db={tx_db} counter={tx_ctr} rx db={rx_db}"); + if tx_ctr >= d.counters { + log!( + " tx counter_index {tx_ctr} out of range ({} counters)", + d.counters + ); + return Err(Status::DEVICE_ERROR); + } + + // Post every RX slot (spec §7.2 step 6). + doorbell(pci, rx_db, d.rx_entries); + + // Link (spec §2.5): Linux does not wait; we poll briefly and log. + let mut link = false; + for _ in 0..LINK_CHECKS { + if reg_rd(pci, regs::DEVICE_STATUS) & DEV_STS_LINK_UP != 0 { + link = true; + break; + } + delay_ms(SLEEP_MS); + } + log!( + "link {}", + if link { + "up" + } else { + "NOT up after 5s (continuing)" + } + ); + + // Stop DMA at ExitBootServices (spec §10.3). Context leaked: lives as long as the event. + let ctx = Box::into_raw(Box::new(EbsCtx { pci, rev })); + match boot::create_event( + EventType::SIGNAL_EXIT_BOOT_SERVICES, + Tpl::NOTIFY, + Some(on_exit_boot_services), + NonNull::new(ctx.cast()), + ) { + Ok(_) => log!("ExitBootServices reset hook armed"), + Err(e) => log!( + "ExitBootServices hook FAILED: {:?} (device left running)", + e.status() + ), + } + + let tx_slots = (d.tx_pages_per_qpl as usize * PAGE / BUF) as u32; + let tx_counter = counters.host.add(tx_ctr as usize * 4) as *const u8; + Ok(Gvnic { + pci, + mtu, + mac: d.mac, + rev, + aq, + counters, + irq_dbs, + qres, + tx: Tx { + counter: tx_counter, + ring: tx_ring, + qpl: tx_qpl, + entries: d.tx_entries, + slots: tx_slots, + req: 0, + done: 0, + db_index: tx_db, + callers: vec![core::ptr::null(); tx_slots as usize], + }, + rx: Rx { + desc: rx_desc, + data: rx_data, + qpl: rx_qpl, + entries: d.rx_entries, + cnt: 0, + fill: d.rx_entries, + seq: 1, + db_index: rx_db, + skip_cont: false, + }, + }) +} diff --git a/crates/gvnic/src/main.rs b/crates/gvnic/src/main.rs new file mode 100644 index 0000000..db54585 --- /dev/null +++ b/crates/gvnic/src/main.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `gvnic.efi` - a UEFI SimpleNetworkProtocol driver for the Google Virtual NIC (gVNIC, +//! PCI `1ae0:0042`, Linux driver name `gve`). +//! +//! GCP's UEFI firmware ships no gVNIC driver (its x86 OVMF has the full NetworkPkg stack +//! -- SNP/MNP/ARP/IP4/DHCP4/UDP4/TCP4 -- but no NIC driver for gVNIC, and no longer one +//! for virtio-net either), while GCP *requires* gVNIC for Confidential VMs and Arm. So the +//! firmware's IP stack never has an SNP to bind to and stage0's `net::bringup()` fails +//! with `IP4_CONFIG2 NOT_FOUND`. This driver fills that gap exactly as `ena.efi` does on +//! EC2: it produces `EFI_SIMPLE_NETWORK_PROTOCOL` on the gVNIC controller and EDK2's +//! existing MNP/IP4/TCP4/UDP4 stack layers on top, so stage0's networking is unchanged. +//! +//! A well-behaved UEFI Driver-Model driver: the entry point only installs a +//! `DriverBinding` and returns; it touches no hardware until the firmware calls `Start()` +//! on a matching gVNIC handle, so on other platforms (EC2/ENA, local QEMU) it sits idle. +//! +//! stage0 loads it from a measured PE section (integrity bound via PCR4, like ena.efi). +//! +//! Device protocol: derived from the Linux `gve` driver (drivers/net/ethernet/google/gve, +//! Copyright Google LLC, `(GPL-2.0 OR MIT)`), used under the MIT terms; reference commit +//! 45e0a63f9c86. See `device.rs`. + +#![no_std] +#![no_main] + +extern crate alloc; + +mod binding; +mod device; +mod pci; +mod snp; + +use uefi::prelude::*; + +#[entry] +fn main() -> Status { + uefi::helpers::init().unwrap(); + // Install the DriverBinding and return SUCCESS. Because the PE subsystem is + // EFI_BOOT_SERVICE_DRIVER, the image stays resident after this returns; the + // firmware (or stage0's connect_all_controllers) calls back into binding::start + // when it connects the gVNIC controller. + match binding::install() { + Ok(()) => { + uefi::println!("gvnic: DriverBinding installed (idle until a gVNIC device binds)"); + Status::SUCCESS + } + Err(e) => { + uefi::println!("gvnic: failed to install DriverBinding: {:?}", e.status()); + e.status() + } + } +} diff --git a/crates/gvnic/src/pci.rs b/crates/gvnic/src/pci.rs new file mode 100644 index 0000000..6c0cdc9 --- /dev/null +++ b/crates/gvnic/src/pci.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Minimal `EFI_PCI_IO_PROTOCOL` binding. uefi/uefi-raw don't expose it, so we +//! hand-roll the vtable. Only the members the NIC drivers (ena, gvnic) use are given real +//! signatures; the unused slots are kept as pointer-sized placeholders so the +//! struct layout (a firmware-provided vtable indexed by offset) stays correct. + +// Map/attribute helpers are wired for the device layer that lands next. +#![allow(dead_code)] + +use core::ffi::c_void; + +use uefi::proto::unsafe_protocol; +use uefi::{guid, Guid, Status}; + +/// `EFI_PCI_IO_PROTOCOL_WIDTH` (the values the driver uses). +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciWidth { + U8 = 0, + U16 = 1, + U32 = 2, + U64 = 3, +} + +/// `EFI_PCI_IO_PROTOCOL_OPERATION` for `Map`. +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciMapOp { + Read = 0, + Write = 1, + CommonBuffer = 2, +} + +/// `EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION`. +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum PciAttrOp { + Get = 0, + Set = 1, + Enable = 2, + Disable = 3, + Supported = 4, +} + +/// `EFI_PCI_IO_ATTRIBUTE_BUS_MASTER`: enable the device as a PCI bus master (required +/// before any DMA / `Map`). NB 0x0400, not 0x0004 (which is VGA_PALETTE_IO). +pub const PCI_ATTR_BUS_MASTER: u64 = 0x0400; + +/// BAR-relative MMIO read/write: `Mem.Read` / `Mem.Write`. +type MemFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + width: PciWidth, + bar_index: u8, + offset: u64, + count: usize, + buffer: *mut c_void, +) -> Status; + +/// PCI config-space read/write: `Pci.Read` / `Pci.Write` (note: u32 offset, no BAR). +type ConfigFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + width: PciWidth, + offset: u32, + count: usize, + buffer: *mut c_void, +) -> Status; + +type MapFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + operation: PciMapOp, + host_address: *const c_void, + number_of_bytes: *mut usize, + device_address: *mut u64, + mapping: *mut *mut c_void, +) -> Status; + +type UnmapFn = + unsafe extern "efiapi" fn(this: *const PciIoProtocol, mapping: *mut c_void) -> Status; + +// alloc_type / memory_type are EFI enums; u32 matches their ABI without importing them. +type AllocBufferFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + alloc_type: u32, + memory_type: u32, + pages: usize, + host_address: *mut *mut c_void, + attributes: u64, +) -> Status; + +type FreeBufferFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + pages: usize, + host_address: *mut c_void, +) -> Status; + +type AttributesFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + operation: PciAttrOp, + attributes: u64, + result: *mut u64, +) -> Status; + +#[repr(C)] +pub struct PciIoAccess { + pub read: MemFn, + pub write: MemFn, +} + +#[repr(C)] +pub struct PciIoConfigAccess { + pub read: ConfigFn, + pub write: ConfigFn, +} + +/// `EFI_PCI_IO_PROTOCOL`. Field order matches the UEFI spec exactly (it is a +/// firmware vtable). Unused members are `usize` placeholders (pointer-sized). +#[repr(C)] +pub struct PciIoProtocol { + poll_mem: usize, + poll_io: usize, + pub mem: PciIoAccess, + pub io: PciIoAccess, + pub pci: PciIoConfigAccess, + copy_mem: usize, + pub map: MapFn, + pub unmap: UnmapFn, + pub allocate_buffer: AllocBufferFn, + pub free_buffer: FreeBufferFn, + flush: usize, + get_location: usize, + pub attributes: AttributesFn, + get_bar_attributes: usize, + set_bar_attributes: usize, + pub rom_size: u64, + pub rom_image: *mut c_void, +} + +impl PciIoProtocol { + pub const GUID: Guid = guid!("4cf5b200-68b8-4ca5-9eec-b23e3f50029a"); +} + +/// High-level wrapper so the protocol works with `boot::open_protocol::`. +#[unsafe_protocol(PciIoProtocol::GUID)] +pub struct PciIo(pub PciIoProtocol); + +impl PciIo { + /// Read PCI config dword 0: low 16 bits = vendor id, high 16 = device id. + pub fn vendor_device(&self) -> uefi::Result<(u16, u16)> { + let mut dw: u32 = 0; + let st = unsafe { + (self.0.pci.read)(&self.0, PciWidth::U32, 0, 1, (&mut dw as *mut u32).cast()) + }; + if st.is_success() { + Ok((dw as u16, (dw >> 16) as u16)) + } else { + Err(st.into()) + } + } +} diff --git a/crates/gvnic/src/snp.rs b/crates/gvnic/src/snp.rs new file mode 100644 index 0000000..68fafca --- /dev/null +++ b/crates/gvnic/src/snp.rs @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! `EFI_SIMPLE_NETWORK_PROTOCOL` production, backed by a [`Gvnic`] device. +//! +//! The SNP interface is the first field of [`SnpDev`], so the firmware-visible +//! `*const SimpleNetworkProtocol` is also a `*mut SnpDev` (the EDK2 "CR" idiom): each +//! member fn recovers the device with `dev(this)`. State machine mirrors VirtioNetDxe: +//! Stopped -> Started -> Initialized. Reset/StationAddress/Statistics/NvData are +//! UNSUPPORTED (as VirtioNetDxe does); the rest drive the gVNIC TX/RX queues. +//! Same shape as ena's snp.rs; differs only in the device type and in taking the +//! advertised max packet size from the device MTU (GCP defaults to 1460, not 1500). + +use alloc::boxed::Box; +use core::ffi::c_void; + +use uefi::boot; +use uefi::{guid, Guid, Handle, Status}; +use uefi_raw::protocol::network::snp::{ + InterruptStatus, NetworkMode, NetworkState, NetworkStatistics, ReceiveFlags, + SimpleNetworkProtocol, +}; +use uefi_raw::{Boolean, IpAddress, MacAddress}; + +use crate::device::Gvnic; + +const SNP_GUID: Guid = guid!("a19832b9-ac25-11d3-9a2d-0090273fc14d"); +const SNP_REVISION: u64 = 0x0001_0000; + +/// SNP interface + its Mode + the owning gVNIC device. `snp` MUST stay first. +#[repr(C)] +pub struct SnpDev { + snp: SimpleNetworkProtocol, + mode: NetworkMode, + nic: Gvnic, +} + +/// Recover the `SnpDev` from a member-fn `this` pointer (snp is at offset 0). +unsafe fn dev<'a>(this: *const SimpleNetworkProtocol) -> &'a mut SnpDev { + &mut *(this as *mut SnpDev) +} + +/// Build the SNP wrapper for `nic`, install it on `controller`, and leak it (the +/// firmware owns it for the controller's life). EDK2's MNP/IP4/TCP4/UDP4 then bind. +pub fn install(controller: Handle, nic: Gvnic) -> uefi::Result<()> { + // Advertise the device MTU as the max packet size (payload, excluding the 14-byte + // media header) so EDK2's IP4 never builds a frame the device would drop. + let mode = build_mode(nic.mac(), nic.mtu); + let dev = Box::new(SnpDev { + snp: SimpleNetworkProtocol { + revision: SNP_REVISION, + start, + stop, + initialize, + reset, + shutdown, + receive_filters, + station_address, + statistics, + multicast_ip_to_mac, + non_volatile_data, + get_status, + transmit, + receive, + wait_for_packet: core::ptr::null_mut(), + mode: core::ptr::null_mut(), + }, + mode, + nic, + }); + let p = Box::into_raw(dev); + unsafe { + (*p).snp.mode = &mut (*p).mode; + boot::install_protocol_interface( + Some(controller), + &SNP_GUID, + (&(*p).snp as *const SimpleNetworkProtocol).cast(), + )?; + } + Ok(()) +} + +fn build_mode(mac: [u8; 6], mtu: u32) -> NetworkMode { + let mut cur = [0u8; 32]; + cur[..6].copy_from_slice(&mac); + let mut bcast = [0u8; 32]; + for b in &mut bcast[..6] { + *b = 0xff; + } + NetworkMode { + state: NetworkState::STOPPED, + hw_address_size: 6, + media_header_size: 14, + max_packet_size: mtu, + nv_ram_size: 0, + nv_ram_access_size: 0, + receive_filter_mask: (ReceiveFlags::UNICAST + | ReceiveFlags::BROADCAST + | ReceiveFlags::MULTICAST) + .bits(), + receive_filter_setting: (ReceiveFlags::UNICAST | ReceiveFlags::BROADCAST).bits(), + max_mcast_filter_count: 0, + mcast_filter_count: 0, + mcast_filter: core::array::from_fn(|_| MacAddress([0u8; 32])), + current_address: MacAddress(cur), + broadcast_address: MacAddress(bcast), + permanent_address: MacAddress(cur), + if_type: 1, // ethernet + mac_address_changeable: Boolean::from(false), + multiple_tx_supported: Boolean::from(false), + media_present_supported: Boolean::from(true), + media_present: Boolean::from(true), + } +} + +unsafe extern "efiapi" fn start(this: *const SimpleNetworkProtocol) -> Status { + let d = dev(this); + if d.mode.state == NetworkState::STOPPED { + d.mode.state = NetworkState::STARTED; + } + Status::SUCCESS +} + +unsafe extern "efiapi" fn stop(this: *const SimpleNetworkProtocol) -> Status { + dev(this).mode.state = NetworkState::STOPPED; + Status::SUCCESS +} + +unsafe extern "efiapi" fn initialize( + this: *const SimpleNetworkProtocol, + _extra_rx: usize, + _extra_tx: usize, +) -> Status { + let d = dev(this); + if d.mode.state == NetworkState::STOPPED { + return Status::NOT_STARTED; + } + d.nic.init_rx(); + d.mode.state = NetworkState::INITIALIZED; + uefi::println!("gvnic: SNP initialized (rx posted, link up)"); + Status::SUCCESS +} + +unsafe extern "efiapi" fn reset(_this: *const SimpleNetworkProtocol, _ext: Boolean) -> Status { + Status::SUCCESS +} + +unsafe extern "efiapi" fn shutdown(this: *const SimpleNetworkProtocol) -> Status { + dev(this).mode.state = NetworkState::STARTED; + Status::SUCCESS +} + +unsafe extern "efiapi" fn receive_filters( + _this: *const SimpleNetworkProtocol, + _enable: ReceiveFlags, + _disable: ReceiveFlags, + _reset_mcast: Boolean, + _mcast_count: usize, + _mcast_filter: *const MacAddress, +) -> Status { + // We receive unicast+broadcast already; accept the request without reprogramming. + Status::SUCCESS +} + +unsafe extern "efiapi" fn station_address( + _this: *const SimpleNetworkProtocol, + _reset: Boolean, + _new: *const MacAddress, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn statistics( + _this: *const SimpleNetworkProtocol, + _reset: Boolean, + _size: *mut usize, + _table: *mut NetworkStatistics, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn multicast_ip_to_mac( + _this: *const SimpleNetworkProtocol, + ipv6: Boolean, + ip: *const IpAddress, + mac: *mut MacAddress, +) -> Status { + if ipv6 != Boolean::from(false) || ip.is_null() || mac.is_null() { + return Status::UNSUPPORTED; // IPv4 only + } + let ipb = ip as *const u8; // first 4 bytes are the v4 octets + let m = mac as *mut u8; // MacAddress is a transparent [u8;32] + m.add(0).write(0x01); + m.add(1).write(0x00); + m.add(2).write(0x5e); + m.add(3).write(ipb.add(1).read() & 0x7f); + m.add(4).write(ipb.add(2).read()); + m.add(5).write(ipb.add(3).read()); + Status::SUCCESS +} + +unsafe extern "efiapi" fn non_volatile_data( + _this: *const SimpleNetworkProtocol, + _read: Boolean, + _offset: usize, + _buffer_size: usize, + _buffer: *mut c_void, +) -> Status { + Status::UNSUPPORTED +} + +unsafe extern "efiapi" fn get_status( + this: *const SimpleNetworkProtocol, + interrupt_status: *mut InterruptStatus, + tx_buf: *mut *mut c_void, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + // Reap a TX completion ONLY when the caller asked for it (TxBuf non-NULL): MNP polls + // GetStatus(.., NULL) for media status, and a completion reaped there is lost, so MNP + // never gets that transmit buffer back. + let completed = if tx_buf.is_null() { + None + } else { + d.nic.poll_tx() + }; + if !tx_buf.is_null() { + *tx_buf = completed + .map(|p| p as *mut c_void) + .unwrap_or(core::ptr::null_mut()); + } + if !interrupt_status.is_null() { + let mut s = InterruptStatus::empty(); + if completed.is_some() { + s |= InterruptStatus::TRANSMIT; + } + *interrupt_status = s; + } + Status::SUCCESS +} + +unsafe extern "efiapi" fn transmit( + this: *const SimpleNetworkProtocol, + header_size: usize, + buffer_size: usize, + buffer: *const c_void, + src: *const MacAddress, + dest: *const MacAddress, + protocol: *const u16, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + let buf = buffer as *mut u8; + // If HeaderSize != 0 the SNP must build the media header into the buffer from + // src/dest/protocol; otherwise the buffer is already a complete frame. + if header_size != 0 { + if header_size < 14 || dest.is_null() || protocol.is_null() { + return Status::INVALID_PARAMETER; + } + // MacAddress is a transparent [u8;32]; use the raw pointer directly (taking a + // reference through the raw deref is UB-adjacent and a hard error now). + core::ptr::copy_nonoverlapping(dest as *const u8, buf, 6); + let src6 = if src.is_null() { + d.nic.mac() + } else { + let mut m = [0u8; 6]; + core::ptr::copy_nonoverlapping(src as *const u8, m.as_mut_ptr(), 6); + m + }; + core::ptr::copy_nonoverlapping(src6.as_ptr(), buf.add(6), 6); + let p = *protocol; + buf.add(12).write_volatile((p >> 8) as u8); + buf.add(13).write_volatile((p & 0xff) as u8); + } + match d.nic.transmit(buf, buffer_size, buffer) { + Ok(()) => Status::SUCCESS, + Err(e) => e, + } +} + +unsafe extern "efiapi" fn receive( + this: *const SimpleNetworkProtocol, + header_size: *mut usize, + buffer_size: *mut usize, + buffer: *mut c_void, + src: *mut MacAddress, + dest: *mut MacAddress, + protocol: *mut u16, +) -> Status { + let d = dev(this); + if d.mode.state != NetworkState::INITIALIZED { + return Status::NOT_STARTED; + } + let cap = *buffer_size; + match d.nic.receive(buffer as *mut u8, cap) { + Some(n) => { + *buffer_size = n; + let b = buffer as *const u8; + if !header_size.is_null() { + *header_size = 14; + } + if !dest.is_null() && n >= 6 { + core::ptr::copy_nonoverlapping(b, dest as *mut u8, 6); + } + if !src.is_null() && n >= 12 { + core::ptr::copy_nonoverlapping(b.add(6), src as *mut u8, 6); + } + if !protocol.is_null() && n >= 14 { + *protocol = ((*b.add(12) as u16) << 8) | (*b.add(13) as u16); + } + Status::SUCCESS + } + None => Status::NOT_READY, + } +} diff --git a/crates/stage0/src/net.rs b/crates/stage0/src/net.rs index c0ac261..07ebac9 100644 --- a/crates/stage0/src/net.rs +++ b/crates/stage0/src/net.rs @@ -16,38 +16,55 @@ const DHCP_POLL_INTERVAL_MS: u64 = 10; /// Give up on DHCP after this long. const DHCP_TIMEOUT_MS: u64 = 30_000; -/// The ENA driver, built per-arch by the Makefile into `build//ena.efi` and -/// embedded unconditionally: stage0 + ena ship as ONE measured unit (the driver is -/// covered by stage0's PCR4, no separate pin). EC2's Nitro firmware ships no ENA -/// driver, so without this there is no SNP for the IP4/TCP4/UDP4 stack to bind. -/// Building stage0 requires `build//ena.efi` to exist (the Makefile builds it -/// first); a missing file is a hard compile error, by design. -#[cfg(target_arch = "x86_64")] -static ENA_DRIVER: &[u8] = include_bytes!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../build/x86_64/ena.efi" -)); -#[cfg(target_arch = "aarch64")] -static ENA_DRIVER: &[u8] = include_bytes!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../build/aarch64/ena.efi" -)); +/// The embedded NIC drivers, built per-arch by the Makefile into `build//*.efi` and +/// embedded unconditionally: stage0 + its drivers ship as ONE measured unit (covered by +/// stage0's PCR4, no separate pin). Each fills a firmware gap: +/// * `ena.efi` -- EC2: Nitro's UEFI firmware ships no ENA driver; +/// * `gvnic.efi` -- GCP: the UEFI firmware ships no gVNIC driver (and GCP requires gVNIC +/// for Confidential VMs and Arm). +/// +/// Without them there is no SNP for the firmware's IP4/TCP4/UDP4 stack to bind. Building +/// stage0 requires the files to exist (the Makefile builds them first); a missing file is a +/// hard compile error, by design. +macro_rules! embedded_driver { + ($name:literal) => {{ + #[cfg(target_arch = "x86_64")] + static D: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../build/x86_64/", + $name + )); + #[cfg(target_arch = "aarch64")] + static D: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../build/aarch64/", + $name + )); + D + }}; +} -/// Load and start any embedded UEFI NIC drivers, before connecting controllers, so a -/// firmware that lacks a driver for its NIC (notably EC2/ENA) still gets an SNP -/// producer. The driver is a well-behaved Driver-Model driver: inert on platforms -/// whose NIC it does not match (GCP virtio-net, local QEMU). +/// Load and start the embedded UEFI NIC drivers, before connecting controllers, so a +/// firmware that lacks a driver for its NIC (EC2/ENA, GCP/gVNIC) still gets an SNP +/// producer. Each is a well-behaved Driver-Model driver: inert on platforms whose NIC it +/// does not match (its Supported() gates on PCI vendor:device). fn load_embedded_drivers() { - crate::slog!( - "stage0: loading embedded ena driver ({} bytes)", - ENA_DRIVER.len() - ); - match crate::secauth::load_image_verified(ENA_DRIVER) { - Ok(handle) => match boot::start_image(handle) { - Ok(()) => crate::slog!("stage0: ena driver started"), - Err(e) => crate::slog!("stage0: ena start_image failed: {:?}", e.status()), - }, - Err(status) => crate::slog!("stage0: ena load_image failed: {status:?}"), + let drivers: [(&str, &[u8]); 2] = [ + ("ena", embedded_driver!("ena.efi")), + ("gvnic", embedded_driver!("gvnic.efi")), + ]; + for (name, image) in drivers { + crate::slog!( + "stage0: loading embedded {name} driver ({} bytes)", + image.len() + ); + match crate::secauth::load_image_verified(image) { + Ok(handle) => match boot::start_image(handle) { + Ok(()) => crate::slog!("stage0: {name} driver started"), + Err(e) => crate::slog!("stage0: {name} start_image failed: {:?}", e.status()), + }, + Err(status) => crate::slog!("stage0: {name} load_image failed: {status:?}"), + } } } @@ -61,6 +78,7 @@ pub fn bringup() -> Result<(), Status> { "stage0: no EFI_IP4_CONFIG2 (firmware lacks the IPv4 stack?): {:?}", e.status() ); + log_net_inventory(); e.status() })?; let mut ip4 = Ip4Config2::new(nic).map_err(|e| e.status())?; @@ -113,6 +131,54 @@ fn dhcp_up(ip4: &mut Ip4Config2) -> Result<(), Status> { } } +/// Failure-path diagnostic (we are about to fail closed anyway): which layer of the UEFI network +/// stack is missing. Logs how many handles carry each layer's protocol, bottom-up (PCI device -> +/// SNP -> MNP -> ARP/IP4 -> IP4Config2/DHCP4 -> UDP4/TCP4), then the name of every loaded +/// driver (DriverBinding handles, named via ComponentName2/1), so "no SNP on the NIC" (no NIC +/// driver), "SNP but no MNP/IP4" (no NetworkPkg stack), and "stack present but unbound" are +/// distinguishable from the serial log alone. +fn log_net_inventory() { + use uefi::proto::driver::ComponentName; + use uefi::{guid, Guid}; + const LAYERS: [(&str, Guid); 9] = [ + ("PciIo", guid!("4cf5b200-68b8-4ca5-9eec-b23e3f50029a")), + ("SNP", guid!("a19832b9-ac25-11d3-9a2d-0090273fc14d")), + ("MNP-SB", guid!("f36ff770-a7e1-42cf-9ed2-56f0f271f44c")), + ("ARP-SB", guid!("f44c00ee-1f2c-4a00-aa09-1c9f3e0800a3")), + ("IP4-SB", guid!("c51711e7-b4bf-404a-bfb8-0a048ef1ffe4")), + ("IP4Config2", guid!("5b446ed1-e30b-4faa-871a-3654eca36080")), + ("DHCP4-SB", guid!("9d9a39d8-bd42-4a73-a4d5-8ee94be11380")), + ("UDP4-SB", guid!("83f01464-99bd-45e5-b383-af6305d8e9e6")), + ("TCP4-SB", guid!("00720665-67eb-4a99-baf7-d3c33a1c7cc9")), + ]; + let count = |g: &Guid| { + boot::locate_handle_buffer(boot::SearchType::ByProtocol(g)) + .map(|h| h.len()) + .unwrap_or(0) + }; + for (name, g) in LAYERS.iter() { + crate::slog!("stage0: net inventory: {name}={}", count(g)); + } + + const DRIVER_BINDING: Guid = guid!("18a031ab-b443-4d1a-a5c0-0c09261e9f71"); + let Ok(drivers) = boot::locate_handle_buffer(boot::SearchType::ByProtocol(&DRIVER_BINDING)) + else { + crate::slog!("stage0: net inventory: no DriverBinding handles"); + return; + }; + crate::slog!("stage0: net inventory: {} drivers loaded:", drivers.len()); + for h in drivers.iter() { + let named = ComponentName::open(*h).ok().and_then(|cn| { + let lang = cn.supported_languages().ok()?.next()?; + cn.driver_name(lang).ok().map(|n| alloc::format!("{n}")) + }); + crate::slog!( + "stage0: net inventory: driver {}", + named.as_deref().unwrap_or("(unnamed)") + ); + } +} + /// Connect all drivers to all handles (best-effort), forcing the firmware to bind /// its network stack so the TCP4/IP4 service bindings become available even on the /// first boot before BDS has connected everything. From db8caabe634084c3c85057d540f3da1cf5b3d443 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:34:51 +0000 Subject: [PATCH 11/21] stage0: signal UDP4 RecycleSignal after copying a datagram out udp_recv() never signalled the RxData RecycleSignal, relying on child destruction to reclaim the buffer. That is not what the UEFI spec requires, and EDK2's Udp4Configure(NULL) ASSERTs the delivered-datagram queue is empty: on firmware built with ASSERTs enabled (GCP) that reset the machine right after every DNS answer, silently (ASSERT output goes to the debug port). Release-built firmware (EC2, local QEMU) compiled the ASSERT away. Verified: GCP DNS resolution now completes (Configure(NULL) SUCCESS, child destroyed, name resolved, payload fetched); local QEMU DNS path unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/stage0/src/udp4.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/stage0/src/udp4.rs b/crates/stage0/src/udp4.rs index 270e805..6bc014b 100644 --- a/crates/stage0/src/udp4.rs +++ b/crates/stage0/src/udp4.rs @@ -309,9 +309,10 @@ fn udp_recv(udp_ptr: *mut Udp4Protocol, budget_ms: u64) -> Result, Statu return Err(st); } - // Copy the datagram out of the (possibly fragmented) receive buffer. We do not - // signal RecycleSignal: this child handles one datagram and is then destroyed, - // which reclaims the buffer. + // Copy the datagram out of the (possibly fragmented) receive buffer, then hand it back + // by signalling RecycleSignal, as the UEFI spec requires. Destroying the child does NOT + // stand in for this: EDK2's Udp4Configure(NULL) ASSERTs the delivered-datagram queue is + // empty, and firmware built with ASSERTs enabled (GCP) resets the machine there. let out = unsafe { let rx = token.packet.rx_data; let mut buf = Vec::new(); @@ -332,6 +333,9 @@ fn udp_recv(udp_ptr: *mut Udp4Protocol, budget_ms: u64) -> Result, Statu )); copied += take; } + if let Some(recycle) = uefi::Event::from_ptr((*rx).recycle_signal) { + let _ = boot::signal_event(&recycle); + } } buf }; From b3df2b04d48a7484421a72041a6546bea437ba10 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:35:07 +0000 Subject: [PATCH 12/21] dbx: emit our own dbx for GCP as a KEK-signed authenticated update Left unset, GCP substitutes its default (Microsoft) dbx, so PCR 7 on GCP depended on a list we don't control and that changes over time. - mkvarstore.py --out-dbx writes the dbx EFI_SIGNATURE_LIST it already enrolls in efi-vars.{ovmf,aws}; --out-dbx-auth (+ --kek-key) wraps it as an EFI_VARIABLE_AUTHENTICATION_2 update signed by our KEK (openssl cms -noattr, fixed timestamp): reproducible for a given key set. build.sh emits build//dbx.esl + dbx.auth.bin; both ship in the release artifacts. - gcp/create.sh passes dbx.auth.bin as --forbidden-database-file. GCP's BIN dbx is an authenticated update (cf. uefi.org DBXUpdate.bin): a bare ESL is accepted at image create but kills every VM at start (hostError). gcloud types the file by extension (.bin -> BIN, else must be DER X.509). --default-dbx (test only) omits it for A/B runs, as a separate -defdbx image. - gcp/create.sh: x86 images also get TDX_CAPABLE; the existing-image check is an exact `images describe` (`images list --filter=name=X` pattern-matched X against X-defdbx and reused the wrong image). Verified on GCP: built dbx.auth.bin is byte-identical to the experiment image that booted; image via create.sh boots (Shielded n2d), PCR7 ee5f65dc (vs c05a3c37 with GCP's default dbx). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 2 ++ tools/build.sh | 4 +++- tools/mkvarstore.py | 46 +++++++++++++++++++++++++++++++++++++ tools/publish/README.md | 11 +++++---- tools/publish/gcp/create.sh | 30 +++++++++++++++++++++--- 5 files changed, 85 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 039e732..a571a1f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -44,6 +44,8 @@ jobs: build/${{ matrix.arch }}/boot.disk build/${{ matrix.arch }}/BOOT*.EFI build/${{ matrix.arch }}/efi-vars.* + build/${{ matrix.arch }}/dbx.esl + build/${{ matrix.arch }}/dbx.auth.bin build/${{ matrix.arch }}/os-release build/${{ matrix.arch }}/*.cer build/${{ matrix.arch }}/*.guid diff --git a/tools/build.sh b/tools/build.sh index 479adcf..86c0e56 100755 --- a/tools/build.sh +++ b/tools/build.sh @@ -104,7 +104,9 @@ python3 "${REPO_ROOT}/tools/mkvarstore.py" --arch "${ARCH}" \ --kek "${KEYDIR}/KEK.crt" --kek-guid "${KEYDIR}/KEK.guid" \ --db "${KEYDIR}/db.crt" --db-guid "${KEYDIR}/db.guid" \ --dict "${REPO_ROOT}/tools/firmware/amznuefi-v0.dict" \ - --out-ovmf "${EFI_VARS_OVMF}" --out-aws "${EFI_VARS_AWS}" + --out-ovmf "${EFI_VARS_OVMF}" --out-aws "${EFI_VARS_AWS}" \ + --out-dbx "${OUTPUT_DIR}/dbx.esl" \ + --out-dbx-auth "${OUTPUT_DIR}/dbx.auth.bin" --kek-key "${KEYDIR}/KEK.crt.key" echo "EFI vars written: ${EFI_VARS_OVMF}" # Emit os-release so the cloud publishers can name/tag the image. BUILD_ID is diff --git a/tools/mkvarstore.py b/tools/mkvarstore.py index 8b7b764..1d9d633 100644 --- a/tools/mkvarstore.py +++ b/tools/mkvarstore.py @@ -17,7 +17,9 @@ import base64 import os import struct +import subprocess import sys +import tempfile import uuid # --- Well-known GUIDs (constants from the UEFI spec / edk2) ------------------ @@ -83,6 +85,35 @@ def sig_list_sha256(digest, owner): + struct.pack("/efi-vars.aws` | EC2 | AWS-format Secure Boot variable store (`--uefi-data`) | | `build//os-release` | both | names/tags the image (`ID`, `VERSION_ID`, `BUILD_ID`) | | `build//{PK,KEK,db}.cer` | GCP | custom Secure Boot keys | +| `build//dbx.auth.bin` | GCP | our dbx (the exact EFI_SIGNATURE_LIST in `efi-vars.*`, also shipped as `dbx.esl`) as a KEK-signed authenticated update -- the only form GCP's `BIN` dbx accepts at VM start | Produce them with `make build-`. Or pass a `v*` release tag as the `version` argument (instead of the default `local`) to download and @@ -107,12 +108,14 @@ tools/publish/gcp/get-console.sh my-vm asia-southeast1-a --follow ``` Uploads `boot.disk` as a `disk.raw` tarball to GCS and creates a global image with -your custom PK/KEK/db and these guest-OS features (idempotent: an existing GCS upload -is reused): +your custom PK/KEK/db/dbx and these guest-OS features (idempotent: an existing GCS upload +is reused). dbx is our own (`dbx.auth.bin`): left unset, GCP fills in its default Microsoft dbx, +which makes PCR 7 depend on a list we don't control (and that changes over time). +`--default-dbx` does exactly that, for A/B measurement only (separate `-defdbx` image): - `UEFI_COMPATIBLE` — required for UEFI boot. -- `SEV_CAPABLE`, `SEV_SNP_CAPABLE` — x86_64 only; mark the image launchable as an AMD - SEV / SEV-SNP Confidential VM. +- `SEV_CAPABLE`, `SEV_SNP_CAPABLE`, `TDX_CAPABLE` — x86_64 only; mark the image launchable + as an AMD SEV / SEV-SNP or Intel TDX Confidential VM. - `GVNIC` — Google Virtual NIC. - aarch64 gets `UEFI_COMPATIBLE` + `GVNIC` only (GCP documents no Arm Confidential VM series; t2a launches as a Shielded VM). diff --git a/tools/publish/gcp/create.sh b/tools/publish/gcp/create.sh index d03a979..e5fd38e 100755 --- a/tools/publish/gcp/create.sh +++ b/tools/publish/gcp/create.sh @@ -30,6 +30,8 @@ Options: --region GCS bucket / zone region (default: ${DEFAULT_REGION}) --public make the image usable by any authenticated GCP user (default) --private keep the image private to this project + --default-dbx TEST ONLY: omit our dbx so GCP fills in its default (Microsoft) dbx; for + dbx A/B measurement runs. Creates a separate '-defdbx' image. --no-verify (release mode) skip gh attestation; fetch the public release asset via curl so no gh install is needed --manifest append created resources to for a teardown script, one per @@ -49,6 +51,7 @@ PROJECT="" REGION="${DEFAULT_REGION}" PUBLIC=true NO_VERIFY=false +DEFAULT_DBX=false MANIFEST="" POSITIONAL=() while [ $# -gt 0 ]; do @@ -60,6 +63,7 @@ while [ $# -gt 0 ]; do --public) PUBLIC=true; shift ;; --private) PUBLIC=false; shift ;; --no-verify) NO_VERIFY=true; shift ;; + --default-dbx) DEFAULT_DBX=true; shift ;; --manifest) MANIFEST="${2:?--manifest needs a value}"; shift 2 ;; --manifest=*) MANIFEST="${1#*=}"; shift ;; -h|--help) usage; exit 0 ;; @@ -147,6 +151,14 @@ fi for c in PK KEK db; do [ -f "${KEYS_DIR}/${c}.cer" ] || die "Secure Boot cert ${c}.cer not found in ${KEYS_DIR}" done +# dbx: the exact EFI_SIGNATURE_LIST mkvarstore.py enrolls into efi-vars.{ovmf,aws}, delivered to +# GCP as a KEK-signed authenticated variable update (dbx.auth.bin) -- the format GCP's BIN dbx +# takes (cf. uefi.org DBXUpdate.bin); a bare ESL is accepted at image create but kills every VM +# at start. Unset, GCP substitutes its own default (Microsoft) dbx. +DBX_FILE="${WORK_DIR}/dbx.auth.bin" +if [ "${DEFAULT_DBX}" != "true" ]; then + [ -f "${DBX_FILE}" ] || die "dbx.auth.bin not found: ${DBX_FILE} (rebuild: make build-${ARCH})" +fi # os-release provides ID, VERSION_ID, BUILD_ID, NAME, PRETTY_NAME (our own artifact). # shellcheck disable=SC1090 @@ -158,18 +170,21 @@ ARCH_DASH=$(echo "${ARCH}" | tr '_' '-') # re-running after a rebuild -- new keys/binary, same VERSION_ID -- makes a new image instead of # silently reusing a stale one. IMAGE_NAME="${ID}-${ARCH_DASH}-${VERSION_DASH}-${BUILD_ID}" +[ "${DEFAULT_DBX}" = "true" ] && IMAGE_NAME="${IMAGE_NAME}-defdbx" IMAGE_DESC="${PRETTY_NAME} version: ${VERSION_ID} build: ${BUILD_ID} arch: ${ARCH}" IMAGE_FAMILY="${ID}" if [ "${ARCH}" = "x86_64" ]; then - GUEST_OS_FEATURES="UEFI_COMPATIBLE,SEV_CAPABLE,SEV_SNP_CAPABLE,GVNIC" + GUEST_OS_FEATURES="UEFI_COMPATIBLE,SEV_CAPABLE,SEV_SNP_CAPABLE,TDX_CAPABLE,GVNIC" else GUEST_OS_FEATURES="UEFI_COMPATIBLE,GVNIC" fi echo "=== Checking for existing image ===" -EXISTING_IMAGE=$(${GCLOUD} compute images list --project="${PROJECT}" \ - --filter="name=${IMAGE_NAME}" --format="value(name)" 2>/dev/null || echo "") +# Exact-name lookup: `images list --filter=name=X` is a pattern match, so X would also match +# X-defdbx (or any longer name) and silently reuse the wrong image. +EXISTING_IMAGE=$(${GCLOUD} compute images describe "${IMAGE_NAME}" --project="${PROJECT}" \ + --format="value(name)" 2>/dev/null || echo "") if [ -n "${EXISTING_IMAGE}" ]; then echo "Image already exists: ${EXISTING_IMAGE}" @@ -206,6 +221,14 @@ else record "gcp gcsobject ${PROJECT} ${GCS_URI}" fi + DBX_ARGS=() + if [ "${DEFAULT_DBX}" = "true" ]; then + echo "WARNING: --default-dbx: GCP's default (Microsoft) dbx, not ours -- test image only" + else + # gcloud types a key file by NAME: `*.bin` -> BIN, anything else must be DER X.509 + # (googlecloudsdk/api_lib/compute/image_utils.py GetFileContentAndFileType). + DBX_ARGS=(--forbidden-database-file="${DBX_FILE}") + fi echo "=== Creating image ${IMAGE_NAME} (${GCP_ARCH}, ${GUEST_OS_FEATURES}) ===" ${GCLOUD} compute images create "${IMAGE_NAME}" --project="${PROJECT}" \ --source-uri="${GCS_URI}" --guest-os-features="${GUEST_OS_FEATURES}" \ @@ -213,6 +236,7 @@ else --platform-key-file="${KEYS_DIR}/PK.cer" \ --key-exchange-key-file="${KEYS_DIR}/KEK.cer" \ --signature-database-file="${KEYS_DIR}/db.cer" \ + "${DBX_ARGS[@]}" \ || die "image create failed" IMAGE_FINAL="${IMAGE_NAME}" record "gcp image ${PROJECT} ${IMAGE_FINAL}" # only when created by this run From aeecd8d47790e6bf0f2575522cc7a0f349aaaf3c Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:35:07 +0000 Subject: [PATCH 13/21] tooling: dev key reuse, verbose stage0 builds, self-ending console follow - HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY=1: reuse build/keys instead of re-minting them, so a rebuilt boot.disk still matches a cloud image already enrolled with those keys (swap the disk, keep the keys). Loud warning at parse time, refused under CI, fails if the keys are missing. Never for a release. - STAGE0_FEATURES=verbose: debug build of stage0 (DNS/TCP/HTTP step logging); changes the measured binary, debug only. - gcp/get-console.sh --follow: poll every 10 s (each gcloud call is a ~1 s Python start-up) and exit once the instance is no longer RUNNING (one last read first), instead of polling a stopped/deleted instance forever. Co-Authored-By: Claude Opus 5.5 --- Makefile | 19 ++++++++++++++++- tools/publish/gcp/get-console.sh | 36 ++++++++++++++++++++++++-------- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/Makefile b/Makefile index c73d195..dd38204 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,9 @@ build/%/stage0.efi build/%/payload.efi build/%/boot.disk STAGE0_DIR = crates/stage0 +# STAGE0_FEATURES=verbose: debug build of stage0 (DNS/TCP/HTTP step logging). Changes the +# measured binary -- debug only, never a release. +STAGE0_FEATURES ?= # Default to the host architecture (uname -m gives x86_64 / aarch64 on Linux), so # bare `make`, `make boot`, `make test` "just work". Override with ARCH=... or by @@ -35,8 +38,22 @@ docker-build-harness: # ---- Secure Boot keys: stage0's own snakeoil PK/KEK/db (regenerated per build) ---- # The pattern rule generates the whole set into build/keys via tools/gen-keys.sh; # release.pem (below) is matched by its explicit rule instead. +# +# HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY=1 -- DEV ITERATION ONLY: reuse the existing build/keys +# instead of re-minting them, so a rebuilt boot.disk still matches a cloud image/varstore already +# enrolled with these keys (fast driver/debug loops: swap the disk, keep the keys). Never for a +# release or any published image: the keys then outlive a single build. Refused under CI. +ifeq ($(HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY),1) +ifneq ($(CI),) +$(error HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY is refused under CI) +endif +$(warning !!! HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY=1: REUSING existing Secure Boot keys in build/keys -- DEV ONLY, never release/publish this build !!!) +build/keys/%: + @test -f $@ || { echo "HAZMAT_WARNING_NO_REGEN_KEYS_DEV_ONLY: $@ missing -- build once without it to mint keys" >&2; exit 1; } +else build/keys/%: docker-build-base $(DOCKER_RUN) $(DOCKER_SAMEUSER) $(BUILD_IMAGE) ./tools/gen-keys.sh build/keys +endif # ---- stage0-sign: this repo's standalone host-side signer (ed25519 keygen + domain-separated # signatures), so stage0 builds + tests without stage1's deploy tool. Built + run in the container. @@ -108,7 +125,7 @@ build/%/gvnic.efi: docker-build-base # driver prerequisites must be built first; nothing extra to pass on the command line. build/%/stage0.efi: build/%/ena.efi build/%/gvnic.efi docker-build-base $(DOCKER_RUN) -e ARCH=$* $(DOCKER_SAMEUSER) $(BUILD_IMAGE) \ - bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path $(STAGE0_DIR)/Cargo.toml --target $*-unknown-uefi && cp -v $(STAGE0_DIR)/target/$*-unknown-uefi/release/stage0.efi $@" + bash -c "mkdir -p build/$* && rustup target add $*-unknown-uefi && cargo build --release --manifest-path $(STAGE0_DIR)/Cargo.toml --target $*-unknown-uefi $(if $(STAGE0_FEATURES),--features $(STAGE0_FEATURES)) && cp -v $(STAGE0_DIR)/target/$*-unknown-uefi/release/stage0.efi $@" # ---- Assemble + db-sign the boot disk (privileged: losetup/mount) ---- build/%/boot.disk: build/%/stage0.efi build/keys/db.crt diff --git a/tools/publish/gcp/get-console.sh b/tools/publish/gcp/get-console.sh index 50a4221..87dd6a7 100755 --- a/tools/publish/gcp/get-console.sh +++ b/tools/publish/gcp/get-console.sh @@ -56,21 +56,39 @@ case "${MODE}" in # --start is a BYTE index; resume from the `next` offset each response reports (it also # stays correct if the serial buffer rolled over and older bytes were dropped). + # Every gcloud call is a full Python start-up (~1s of CPU), so poll every 10s, and only + # when a poll brings nothing new ask for the instance status: once it is no longer + # RUNNING (stage0 powered off / stopped / deleted) do one last read and exit, instead of + # polling a dead instance forever. command -v jq >/dev/null 2>&1 || { echo "Error: --follow needs jq"; exit 1; } NEXT=0 - while true; do - RESP=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ + read_once() { + local resp n got=1 + resp=$(${GCLOUD} compute instances get-serial-port-output "${INSTANCE_NAME}" \ --zone="${ZONE}" \ --project="${PROJECT}" \ --start="${NEXT}" --format=json 2>/dev/null || echo "") - - if [ -n "${RESP}" ]; then - jq -j '.contents // ""' <<<"${RESP}" - N=$(jq -r '.next // empty' <<<"${RESP}") - [ -n "${N}" ] && NEXT="${N}" + if [ -n "${resp}" ]; then + jq -j '.contents // ""' <<<"${resp}" + n=$(jq -r '.next // empty' <<<"${resp}") + if [ -n "${n}" ] && [ "${n}" != "${NEXT}" ]; then NEXT="${n}"; got=0; fi fi - - sleep 2 + return "${got}" + } + while true; do + if ! read_once; then + STATUS=$(${GCLOUD} compute instances describe "${INSTANCE_NAME}" \ + --zone="${ZONE}" --project="${PROJECT}" \ + --format="value(status)" 2>/dev/null || echo "GONE") + if [ "${STATUS:-GONE}" != "RUNNING" ] && [ "${STATUS}" != "PROVISIONING" ] \ + && [ "${STATUS}" != "STAGING" ]; then + read_once || true + echo + echo "--- ${INSTANCE_NAME} is ${STATUS:-GONE}; stopped following ---" + exit 0 + fi + fi + sleep 10 done ;; From 9331e1f0092cd353e8e05863f5b6ffde07c2cdeb Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:18:53 +0000 Subject: [PATCH 14/21] keys: use GCP's fixed signature owner GUID for PK/KEK/db GCP wraps the PK/KEK/db certificates we upload into EFI_SIGNATURE_LISTs with a fixed SignatureOwner, d281fad2-8d88-47a4-9792-5baa47bb1b89 (undocumented; present in the GCE event logs in go-tpm-tools' test data). gen-keys.sh used a random uuidgen GUID per key, so our efi-vars.* ESLs differed from GCP's by those 16 bytes and PCR7 differed per provider (GCP ee5f65dc, QEMU 965cb27a) even with byte-identical dbx. Write GCP's GUID for all three keys. The ESLs are now byte-identical to what GCP enrolls, and PCR7 is one value everywhere: QEMU now measures ee5f65dc, matching GCP, with PCR0-6 and PCR14 unchanged. An offline replay of SecureBoot, PK, KEK, db, dbx, separator, and the db authority reproduces both the old and new values exactly. The owner GUID is metadata only; firmware never uses it for verification. Co-Authored-By: Claude Opus 5.5 --- tools/gen-keys.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/gen-keys.sh b/tools/gen-keys.sh index 4707698..e267df0 100755 --- a/tools/gen-keys.sh +++ b/tools/gen-keys.sh @@ -18,7 +18,11 @@ for name in PK KEK db; do -keyout "$OUT/$name.crt.key" -new -x509 -sha256 -days 3650 \ -subj "/CN=Lock.Boot/" -out "$OUT/$name.crt" openssl x509 -outform DER -in "$OUT/$name.crt" -out "$OUT/$name.cer" - uuidgen > "$OUT/$name.guid" + # Signature owner GUID: the fixed one GCP stamps on every X.509 cert it wraps into an + # EFI_SIGNATURE_LIST for PK/KEK/db (undocumented; seen in GCE event logs 2022-2026). Using + # it here makes our efi-vars.* ESLs byte-identical to what GCP enrolls from the .cer files, + # so PCR7 is one value on QEMU, EC2 and GCP. Metadata only: never used for verification. + echo d281fad2-8d88-47a4-9792-5baa47bb1b89 > "$OUT/$name.guid" done echo "Secure Boot keys written to $OUT (PK, KEK, db)" From 5feb45f499816abaecee1e22b0a6aed4b49c4ea4 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:18:53 +0000 Subject: [PATCH 15/21] publish: create.sh exits 0 on success; tag EC2 instances Project=lockboot create.sh (ec2 + gcp): the EXIT trap's cleanup loop ended on a failing `[ -n "$p" ] && ...` when there was nothing to clean (local builds), so the script exited 1 after a successful run. Use `[ -z "$p" ] || ...`. ec2/launch.sh: tag every instance Project=lockboot. The deploy role (workspace tools/deploy/aws-iam.sh) only allows Start/Stop/Reboot on instances carrying that tag, and can only tag instances at launch. Co-Authored-By: Claude Opus 5.5 --- tools/publish/ec2/create.sh | 2 +- tools/publish/ec2/launch.sh | 4 +++- tools/publish/gcp/create.sh | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tools/publish/ec2/create.sh b/tools/publish/ec2/create.sh index d00d7d7..e474fe0 100755 --- a/tools/publish/ec2/create.sh +++ b/tools/publish/ec2/create.sh @@ -101,7 +101,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Single cleanup hook for every temp path we create. CLEANUP=() -cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -n "$p" ] && rm -rf "$p"; done; } +cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -z "$p" ] || rm -rf "$p"; done; } trap cleanup EXIT # Save real stdout on fd 3 and route everything else to stderr, so the only thing diff --git a/tools/publish/ec2/launch.sh b/tools/publish/ec2/launch.sh index 74ca7c9..534c653 100755 --- a/tools/publish/ec2/launch.sh +++ b/tools/publish/ec2/launch.sh @@ -130,7 +130,9 @@ RUN_ARGS=( --instance-type "${INSTANCE_TYPE}" --user-data "file://${CONFIG_FILE}" --instance-initiated-shutdown-behavior "${SHUTDOWN_BEHAVIOR}" - --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}}]" + # Project=lockboot: the deploy role (workspace tools/deploy/aws-iam.sh) only lets you + # start/stop/reboot instances carrying it. + --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${NAME}},{Key=Project,Value=lockboot}]" ) if [ "${SPOT}" = "true" ]; then RUN_ARGS+=(--instance-market-options '{"MarketType":"spot","SpotOptions":{"SpotInstanceType":"one-time"}}') diff --git a/tools/publish/gcp/create.sh b/tools/publish/gcp/create.sh index e5fd38e..8ae815c 100755 --- a/tools/publish/gcp/create.sh +++ b/tools/publish/gcp/create.sh @@ -99,7 +99,7 @@ ${GCLOUD} auth list --filter=status:ACTIVE --format="value(account)" 2>/dev/null [ -n "${PROJECT}" ] || die "no project (pass --project or run: ${GCLOUD} config set project )" CLEANUP=() -cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -n "$p" ] && rm -rf "$p"; done; } +cleanup() { local p; for p in "${CLEANUP[@]:-}"; do [ -z "$p" ] || rm -rf "$p"; done; } trap cleanup EXIT # Save real stdout on fd 3 and route everything else to stderr, so the only thing From 315e8de84164de6a70f2758b0f2030d959a923c6 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Fri, 6 Nov 2026 17:10:41 +0000 Subject: [PATCH 16/21] pcrs: reproduce stage0's PCRs from its release artifacts; ship pcrs.json tools/predict-pcrs.py computes the PCRs at stage0's payload handoff from BOOT*.EFI, boot.disk, *.cer, *.guid and dbx.esl alone, by replaying the event sequence the firmware logs: - PCR3, PCR6: separator only. - PCR4: "Calling EFI Application from Boot Option", separator, and the Authenticode hash of the signed BOOT*.EFI. The embedded NIC drivers and the payload load through stage0's Security2 override, which bypasses firmware image measurement (drivers are inside stage0's hash; the payload is in PCR14). - PCR5: separator, UEFI_GPT_DATA of boot.disk. - PCR7: SecureBoot, PK, KEK, db, dbx, separator, and the db authority that verified stage0, with the ESLs rebuilt by mkvarstore.py's code. - PCR14 (with --payload-sha256): stage0's H_bank(sha256(payload)). PCR0-2 (provider firmware, boot entries, ROMs) are left to golden readings. --check compares against a test-payload serial log. build.sh writes build//pcrs.json (sha256 + sha384, vaportpm layout); CI uploads it, so it ships in the attested release zips. The test payload also dumps the TCG2 event log (best effort; EC2 does not provide one), to diagnose a prediction mismatch event by event. Verified, all predicted PCRs in sha1/sha256/sha384/sha512: QEMU x86_64 and aarch64; GCP final + dbx runs (sha256/sha384, PCR3-7,14); GCP Shielded n2d, SEV, SEV-SNP, c3 (PCR3-6,14; PCR7 differs only because those images carried GCP's default dbx). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 1 + crates/stage0-test-payload/src/main.rs | 41 +++++ tools/build.sh | 5 + tools/predict-pcrs.py | 201 +++++++++++++++++++++++++ 4 files changed, 248 insertions(+) create mode 100755 tools/predict-pcrs.py diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a571a1f..55c8850 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,6 +46,7 @@ jobs: build/${{ matrix.arch }}/efi-vars.* build/${{ matrix.arch }}/dbx.esl build/${{ matrix.arch }}/dbx.auth.bin + build/${{ matrix.arch }}/pcrs.json build/${{ matrix.arch }}/os-release build/${{ matrix.arch }}/*.cer build/${{ matrix.arch }}/*.guid diff --git a/crates/stage0-test-payload/src/main.rs b/crates/stage0-test-payload/src/main.rs index 78d0966..910c3e8 100644 --- a/crates/stage0-test-payload/src/main.rs +++ b/crates/stage0-test-payload/src/main.rs @@ -63,6 +63,10 @@ fn main() -> Status { Ok(()) => {} Err(e) => println!("payload: could not read PCRs: {e}"), } + // Best effort: some firmware (EC2) does not hand out its log; the PCR dump above stands alone. + if let Err(e) = print_event_log() { + println!("payload: could not read TCG2 event log: {e}"); + } // Experiment: attempt the User -> Deployed Mode transition from here (pre-ExitBootServices, // the same position stage0 would do it from), AFTER this boot's PCRs were dumped, so the next @@ -208,3 +212,40 @@ fn print_pcrs() -> Result<()> { println!("payload: ===PCR-DUMP-END==="); Ok(()) } + +/// Dump the firmware's TCG2 (crypto-agile) event log, so the PCR predictor's event sequence can +/// be checked against what the firmware actually measured. Per event, bracketed by stable markers: +/// payload: EV +/// payload: EVD (one per bank) +/// payload: EVX (event data, <= 64 bytes per line, in order) +fn print_event_log() -> Result<()> { + let handle = boot::get_handle_for_protocol::() + .map_err(|e| anyhow!("no EFI_TCG2_PROTOCOL: {:?}", e.status()))?; + let mut tcg = boot::open_protocol_exclusive::(handle) + .map_err(|e| anyhow!("open EFI_TCG2_PROTOCOL: {:?}", e.status()))?; + let log = tcg + .get_event_log_v2() + .map_err(|e| anyhow!("GetEventLog(TCG_2): {:?}", e.status()))?; + + println!("payload: ===EVENTLOG-BEGIN==="); + let mut n = 0usize; + for ev in log.iter() { + println!( + "payload: EV {n} {} {:08x}", + ev.pcr_index().0, + ev.event_type().0 + ); + for (alg, digest) in ev.digests() { + println!("payload: EVD {n} {:04x} {}", alg.0, hex::encode(digest)); + } + for chunk in ev.event_data().chunks(64) { + println!("payload: EVX {n} {}", hex::encode(chunk)); + } + n += 1; + } + println!( + "payload: ===EVENTLOG-END=== events={n} truncated={}", + log.is_truncated() + ); + Ok(()) +} diff --git a/tools/build.sh b/tools/build.sh index 86c0e56..7b924aa 100755 --- a/tools/build.sh +++ b/tools/build.sh @@ -128,6 +128,11 @@ for f in db.cer db.guid PK.cer PK.guid KEK.cer KEK.guid; do [ -f "${KEYDIR}/${f}" ] && cp "${KEYDIR}/${f}" "${OUTPUT_DIR}/" done +# Predicted PCRs (3-7) at stage0's payload handoff, reproduced from the artifacts above alone +# (BOOT*.EFI, boot.disk, *.cer, *.guid, dbx.esl): the reference a verifier checks a quote against. +python3 "${REPO_ROOT}/tools/predict-pcrs.py" "${OUTPUT_DIR}" --out "${OUTPUT_DIR}/pcrs.json" +echo "Predicted PCRs written: ${OUTPUT_DIR}/pcrs.json" + if [ -n "${OWNER_UID:-}" ] && [ -n "${OWNER_GID:-}" ]; then chown -R "${OWNER_UID}:${OWNER_GID}" "${OUTPUT_DIR}" fi diff --git a/tools/predict-pcrs.py b/tools/predict-pcrs.py new file mode 100755 index 0000000..1a6c90c --- /dev/null +++ b/tools/predict-pcrs.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +# Reproduce stage0's PCR values from its release artifacts -- the root of the verification path. +# +# Given a stage0 build/release directory, compute the PCRs the firmware will hold when stage0 +# hands off to its payload (before ExitBootServices), per bank, by replaying the exact event +# sequence UEFI firmware logs (confirmed event-by-event against the OVMF event log and the GCE +# logs in go-tpm-tools' test data; values match QEMU and GCP across sha1/sha256/sha384/sha512): +# +# PCR3, PCR6 EV_SEPARATOR only (nothing else is measured there). +# PCR4 EV_EFI_ACTION "Calling EFI Application from Boot Option", EV_SEPARATOR, +# EV_EFI_BOOT_SERVICES_APPLICATION = Authenticode hash of the signed BOOT*.EFI. +# (The embedded NIC drivers and the payload are loaded through stage0's own +# Security2 override, which bypasses the firmware's image measurement: the +# drivers are covered by stage0's own hash, the payload by PCR14.) +# PCR5 EV_SEPARATOR, EV_EFI_GPT_EVENT = UEFI_GPT_DATA of boot.disk +# (header || NumberOfPartitions || the non-empty partition entries). +# PCR7 SecureBoot=1, PK, KEK, db, dbx (EV_EFI_VARIABLE_DRIVER_CONFIG, the enrolled ESLs), +# EV_SEPARATOR, then EV_EFI_VARIABLE_AUTHORITY = the db entry that verified stage0. +# The ESLs are rebuilt with mkvarstore.py's own code; on GCP they are +# byte-identical because the owner GUID is GCP's (see gen-keys.sh). +# PCR14 (with --payload-sha256) stage0's direct TPM2_PCR_Extend of the payload digest: +# not in the event log; event digest = H_bank(sha256(payload)). +# +# Not reproduced, by design: PCR0 (firmware code), PCR1 (firmware-created boot entries), PCR2 +# (option ROMs / platform drivers). They measure the provider's own firmware and configuration, +# which sits inside the trust boundary the provider's vTPM already implies, and they change with +# provider firmware updates -- record them as per-instance-type golden readings, never bind keys +# to them. +# +# Output (vaportpm JSON layout): {"pcrs": {"sha256": {"4": "", ...}, "sha384": {...}}} +# +# usage: predict-pcrs.py [--payload-sha256 HEX] [--banks sha256,sha384] [--out F] +# predict-pcrs.py --check (compare against the test payload's +# "payload: PCR " dump) +import argparse +import hashlib +import json +import os +import re +import struct +import sys +import uuid + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import mkvarstore as mv # noqa: E402 + +BOOT_EFI = {"x86_64": "BOOTX64.EFI", "aarch64": "BOOTAA64.EFI"} +SECTOR = 512 + + +# --- event payloads (the data each event's digest is computed over) ----------------------------- +def uefi_variable_data(vendor, name, data): + """UEFI_VARIABLE_DATA: VariableName GUID, UnicodeNameLength, VariableDataLength, name, data.""" + n = name.encode("utf-16-le") + return vendor.bytes_le + struct.pack(" done: + h.update(pe[done:end]) + return h.digest() + + +def gpt_data(disk_path): + """UEFI_GPT_DATA: the primary GPT header, entry count, then the non-empty entries.""" + with open(disk_path, "rb") as f: + f.seek(SECTOR) + hdr = f.read(SECTOR) + if hdr[:8] != b"EFI PART": + raise SystemExit(f"{disk_path}: no GPT header at LBA 1") + hsize, = struct.unpack_from(" Date: Mon, 9 Nov 2026 16:43:16 +0000 Subject: [PATCH 17/21] pcrs: emit stage0.replay.json (pcr-replay/v1) alongside the reference pcrs.json tools/predict-pcrs.py now writes stage0's PCR replay file -- every event stage0 and the firmware add between reset and the stage1 handoff, each with its derivation from the build artifacts and the digests computed here -- plus the vaportpm-format pcrs.json reference, replayed from those digests. Format and verifier: workspace tools/pcr-replay. build.sh writes both; CI uploads stage0.replay.json with the build. Verified: make build-x86_64/aarch64 writes both files; on GCP n2d-standard-2 Shielded the probe's PCRs reproduce with the workspace GCP platform file + this stage0.replay.json (all non-ACPI events re-derived), and the full stage0 -> UKI -> stage2 chain verifies on GCP SEV and SEV-SNP. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 1 + tools/build.sh | 10 +- tools/predict-pcrs.py | 219 ++++++++++++++++++++---------------- 3 files changed, 131 insertions(+), 99 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 55c8850..d0b0510 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,6 +47,7 @@ jobs: build/${{ matrix.arch }}/dbx.esl build/${{ matrix.arch }}/dbx.auth.bin build/${{ matrix.arch }}/pcrs.json + build/${{ matrix.arch }}/stage0.replay.json build/${{ matrix.arch }}/os-release build/${{ matrix.arch }}/*.cer build/${{ matrix.arch }}/*.guid diff --git a/tools/build.sh b/tools/build.sh index 7b924aa..70cbeec 100755 --- a/tools/build.sh +++ b/tools/build.sh @@ -128,10 +128,12 @@ for f in db.cer db.guid PK.cer PK.guid KEK.cer KEK.guid; do [ -f "${KEYDIR}/${f}" ] && cp "${KEYDIR}/${f}" "${OUTPUT_DIR}/" done -# Predicted PCRs (3-7) at stage0's payload handoff, reproduced from the artifacts above alone -# (BOOT*.EFI, boot.disk, *.cer, *.guid, dbx.esl): the reference a verifier checks a quote against. -python3 "${REPO_ROOT}/tools/predict-pcrs.py" "${OUTPUT_DIR}" --out "${OUTPUT_DIR}/pcrs.json" -echo "Predicted PCRs written: ${OUTPUT_DIR}/pcrs.json" +# stage0's PCR replay file (pcr-replay/v1: every event from TPM reset to the payload handoff, +# derived from the artifacts above -- BOOT*.EFI, boot.disk, *.cer, *.guid, dbx.esl) and the +# reference PCRs it replays to (pcrs.json, vaportpm layout). See tools/predict-pcrs.py. +python3 "${REPO_ROOT}/tools/predict-pcrs.py" "${OUTPUT_DIR}" \ + --replay "${OUTPUT_DIR}/stage0.replay.json" --out "${OUTPUT_DIR}/pcrs.json" +echo "PCR replay file written: ${OUTPUT_DIR}/stage0.replay.json (reference: pcrs.json)" if [ -n "${OWNER_UID:-}" ] && [ -n "${OWNER_GID:-}" ]; then chown -R "${OWNER_UID}:${OWNER_GID}" "${OUTPUT_DIR}" diff --git a/tools/predict-pcrs.py b/tools/predict-pcrs.py index 1a6c90c..70a8adc 100755 --- a/tools/predict-pcrs.py +++ b/tools/predict-pcrs.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 -# Reproduce stage0's PCR values from its release artifacts -- the root of the verification path. +# stage0's PCR replay file -- the root of the verification path. # -# Given a stage0 build/release directory, compute the PCRs the firmware will hold when stage0 -# hands off to its payload (before ExitBootServices), per bank, by replaying the exact event -# sequence UEFI firmware logs (confirmed event-by-event against the OVMF event log and the GCE -# logs in go-tpm-tools' test data; values match QEMU and GCP across sha1/sha256/sha384/sha512): +# Given a stage0 build/release directory, write the events that UEFI firmware and stage0 extend +# from TPM reset to stage0's payload handoff (before ExitBootServices), as a pcr-replay/v1 file +# (format and verifier: workspace tools/pcr-replay). Each event carries a derivation from the +# release artifacts AND the digests computed here, independently, so a replay cross-checks both. +# Confirmed event-by-event against the OVMF event log and GCE event logs, sha1/256/384/512. # # PCR3, PCR6 EV_SEPARATOR only (nothing else is measured there). # PCR4 EV_EFI_ACTION "Calling EFI Application from Boot Option", EV_SEPARATOR, @@ -12,50 +13,50 @@ # (The embedded NIC drivers and the payload are loaded through stage0's own # Security2 override, which bypasses the firmware's image measurement: the # drivers are covered by stage0's own hash, the payload by PCR14.) -# PCR5 EV_SEPARATOR, EV_EFI_GPT_EVENT = UEFI_GPT_DATA of boot.disk -# (header || NumberOfPartitions || the non-empty partition entries). -# PCR7 SecureBoot=1, PK, KEK, db, dbx (EV_EFI_VARIABLE_DRIVER_CONFIG, the enrolled ESLs), -# EV_SEPARATOR, then EV_EFI_VARIABLE_AUTHORITY = the db entry that verified stage0. +# PCR5 EV_SEPARATOR, EV_EFI_GPT_EVENT = UEFI_GPT_DATA of boot.disk. +# PCR7 SecureBoot, PK, KEK, db, dbx (EV_EFI_VARIABLE_DRIVER_CONFIG, the enrolled ESLs), +# EV_SEPARATOR, EV_EFI_VARIABLE_AUTHORITY = the db entry that verified stage0. # The ESLs are rebuilt with mkvarstore.py's own code; on GCP they are # byte-identical because the owner GUID is GCP's (see gen-keys.sh). -# PCR14 (with --payload-sha256) stage0's direct TPM2_PCR_Extend of the payload digest: -# not in the event log; event digest = H_bank(sha256(payload)). +# PCR14 stage0's direct TPM2_PCR_Extend of its payload: H_bank(sha256(payload)), not +# logged. An input (the payload is the deployment's choice). +# PCR8-13, 15-23 not extended. # -# Not reproduced, by design: PCR0 (firmware code), PCR1 (firmware-created boot entries), PCR2 -# (option ROMs / platform drivers). They measure the provider's own firmware and configuration, -# which sits inside the trust boundary the provider's vTPM already implies, and they change with -# provider firmware updates -- record them as per-instance-type golden readings, never bind keys -# to them. +# Not modelled: PCR0-2 (provider firmware code, firmware boot entries, option ROMs). They are the +# platform's, inside the trust boundary its vTPM already implies, and change with its firmware +# updates: a per-platform replay file (golden readings) supplies them. # -# Output (vaportpm JSON layout): {"pcrs": {"sha256": {"4": "", ...}, "sha384": {...}}} +# Also writes pcrs.json (vaportpm layout): replaying this file alone, i.e. every PCR it models +# except the payload-dependent PCR14 -- the reference a verifier compares a quote against. # -# usage: predict-pcrs.py [--payload-sha256 HEX] [--banks sha256,sha384] [--out F] -# predict-pcrs.py --check (compare against the test payload's -# "payload: PCR " dump) +# usage: predict-pcrs.py [--banks sha256,sha384] --replay F [--out pcrs.json] +from __future__ import annotations + import argparse import hashlib import json import os -import re import struct import sys import uuid +from typing import Any sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import mkvarstore as mv # noqa: E402 BOOT_EFI = {"x86_64": "BOOTX64.EFI", "aarch64": "BOOTAA64.EFI"} SECTOR = 512 +SEPARATOR = b"\0\0\0\0" +CALLING = "Calling EFI Application from Boot Option" # --- event payloads (the data each event's digest is computed over) ----------------------------- -def uefi_variable_data(vendor, name, data): +def uefi_variable_data(vendor: uuid.UUID, name: str, data: bytes) -> bytes: """UEFI_VARIABLE_DATA: VariableName GUID, UnicodeNameLength, VariableDataLength, name, data.""" - n = name.encode("utf-16-le") - return vendor.bytes_le + struct.pack(" bytes: """Authenticode PE image hash (the digest firmware logs for a loaded image).""" pe_off = struct.unpack_from(" bytes: """UEFI_GPT_DATA: the primary GPT header, entry count, then the non-empty entries.""" with open(disk_path, "rb") as f: f.seek(SECTOR) @@ -103,98 +104,126 @@ def gpt_data(disk_path): return hdr[:hsize] + struct.pack(" bytes: with open(os.path.join(d, name), "rb") as f: return f.read() -def owner(d, role): +def owner(d: str, role: str) -> uuid.UUID: return uuid.UUID(read(d, f"{role}.guid").decode().strip()) -def detect_arch(d): +def detect_arch(d: str) -> str: found = [a for a, f in BOOT_EFI.items() if os.path.exists(os.path.join(d, f))] if len(found) != 1: raise SystemExit(f"{d}: expected exactly one of {sorted(BOOT_EFI.values())}") return found[0] -def predict(d, banks, payload_sha256=None): +def replay_file(d: str, banks: list[str]) -> dict[str, Any]: arch = detect_arch(d) - efi = read(d, BOOT_EFI[arch]) + efi_name = BOOT_EFI[arch] + files = {n: read(d, n) for n in (efi_name, "boot.disk", "PK.cer", "KEK.cer", "db.cer", "dbx.esl")} gpt = gpt_data(os.path.join(d, "boot.disk")) - pk, kek, db = read(d, "PK.cer"), read(d, "KEK.cer"), read(d, "db.cer") - db_owner = owner(d, "db") - pcr7_events = [ - uefi_variable_data(mv.EFI_GLOBAL_VARIABLE, "SecureBoot", b"\x01"), - uefi_variable_data(mv.EFI_GLOBAL_VARIABLE, "PK", mv.sig_list_x509(pk, owner(d, "PK"))), - uefi_variable_data(mv.EFI_GLOBAL_VARIABLE, "KEK", mv.sig_list_x509(kek, owner(d, "KEK"))), - uefi_variable_data(mv.IMAGE_SECURITY_DATABASE, "db", mv.sig_list_x509(db, db_owner)), - uefi_variable_data(mv.IMAGE_SECURITY_DATABASE, "dbx", read(d, "dbx.esl")), - None, # separator - # EV_EFI_VARIABLE_AUTHORITY: the EFI_SIGNATURE_DATA (owner || cert) that verified stage0 - uefi_variable_data(mv.IMAGE_SECURITY_DATABASE, "db", db_owner.bytes_le + db), + own = {r: owner(d, r) for r in ("PK", "KEK", "db")} + + def var(vendor: uuid.UUID, name: str, data_expr: dict[str, Any]) -> dict[str, Any]: + return {"uefi_variable": {"vendor": str(vendor), "name": name, "data": data_expr}} + + def esl(role: str) -> dict[str, Any]: + return {"efi_signature_list": {"type": "x509", "owner": str(own[role]), + "data": {"artifact": f"{role}.cer"}}} + + sep_expr = {"hex": SEPARATOR.hex()} + # (pcr, type, by, about, derivation, digest mode, bytes for the local computation) + G, S = mv.EFI_GLOBAL_VARIABLE, mv.IMAGE_SECURITY_DATABASE + ev: list[tuple[int, str, str, str, dict[str, Any], str, bytes]] = [ + (3, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_EFI_ACTION", "firmware", "boot option dispatch", {"utf8": CALLING}, "hash", CALLING.encode()), + (4, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_EFI_BOOT_SERVICES_APPLICATION", "firmware", f"stage0 ({efi_name}, Authenticode)", + {"artifact": efi_name}, "authenticode", files[efi_name]), + (5, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (5, "EV_EFI_GPT_EVENT", "firmware", "UEFI_GPT_DATA of boot.disk", + {"gpt": {"artifact": "boot.disk"}}, "hash", gpt), + (6, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "SecureBoot = 1", + var(G, "SecureBoot", {"hex": "01"}), "hash", uefi_variable_data(G, "SecureBoot", b"\x01")), ] - - out = {} - for bank in banks: - H = getattr(hashlib, bank) - sep = H(b"\0\0\0\0").digest() - - def chain(digests): - v = b"\0" * H().digest_size - for e in digests: - v = H(v + e).digest() - return v.hex() - - p = { - 3: chain([sep]), - 4: chain([H(b"Calling EFI Application from Boot Option").digest(), sep, - authenticode(efi, H)]), - 5: chain([sep, H(gpt).digest()]), - 6: chain([sep]), - 7: chain([sep if e is None else H(e).digest() for e in pcr7_events]), - } - if payload_sha256: - p[14] = chain([H(bytes.fromhex(payload_sha256)).digest()]) - out[bank] = {str(k): v for k, v in sorted(p.items())} + for role, vendor in (("PK", G), ("KEK", G), ("db", S)): + ev.append((7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", f"{role}: one x509 ESL ({role}.cer)", + var(vendor, role, esl(role)), "hash", + uefi_variable_data(vendor, role, mv.sig_list_x509(files[f"{role}.cer"], own[role])))) + ev += [ + (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "dbx (dbx.esl)", + var(S, "dbx", {"artifact": "dbx.esl"}), "hash", uefi_variable_data(S, "dbx", files["dbx.esl"])), + (7, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (7, "EV_EFI_VARIABLE_AUTHORITY", "firmware", "the db entry that verified stage0", + var(S, "db", {"concat": [{"guid": str(own["db"])}, {"artifact": "db.cer"}]}), "hash", + uefi_variable_data(S, "db", own["db"].bytes_le + files["db.cer"])), + ] + events: list[dict[str, Any]] = [] + for pcr, typ, by, about, expr, mode, data in ev: + e: dict[str, Any] = {"pcr": pcr, "type": typ, "by": by} + if about: + e["about"] = about + e["derive"] = expr + if mode != "hash": + e["digest"] = mode + e["digests"] = {b: (authenticode(data, getattr(hashlib, b)) if mode == "authenticode" + else getattr(hashlib, b)(data).digest()).hex() for b in banks} + events.append(e) + events.append({"pcr": 14, "type": "unlogged", "by": "stage0", + "about": "the payload stage0 verified and runs: H_bank(sha256(payload))", + "derive": {"input": "payload"}}) + return { + "schema": "pcr-replay/v1", + "name": f"stage0 {arch}", + "about": "UEFI firmware and stage0, from TPM reset to the payload handoff (before " + "ExitBootServices). PCR0-2 are the platform's (a platform replay file).", + "artifacts": {n: {"sha256": hashlib.sha256(b).hexdigest()} for n, b in files.items()}, + "entry": efi_name, + "inputs": {"payload": {"about": "sha256 of the payload stage0 runs (the next stage)", + "next_entry": True}}, + "reset": list(range(3, 24)), + "unextended": [0, 1, 2], + "events": events, + } + + +def reference_pcrs(rf: dict[str, Any], banks: list[str]) -> dict[str, Any]: + """Replay the file's embedded digests from reset: every PCR it models except PCR14.""" + out: dict[str, dict[str, str]] = {} + for b in banks: + H = getattr(hashlib, b) + n = H().digest_size + p = {k: (b"\xff" if 17 <= k <= 22 else b"\0") * n for k in rf["reset"] if k != 14} + for e in rf["events"]: + if e["pcr"] in p: + p[e["pcr"]] = H(p[e["pcr"]] + bytes.fromhex(e["digests"][b])).digest() + out[b] = {str(k): v.hex() for k, v in sorted(p.items())} return {"pcrs": out} -def check(pred, log_path): - with open(log_path, "rb") as f: - txt = f.read().decode("latin1") - seen = {(a, int(i)): v for a, i, v in re.findall(r"payload: PCR (\w+) (\d\d) ([0-9a-f]+)", txt)} - bad = 0 - for bank, pcrs in pred["pcrs"].items(): - for i, want in pcrs.items(): - got = seen.get((bank, int(i))) - status = "ok" if got == want else ("MISSING" if got is None else "MISMATCH") - bad += status != "ok" - print(f"{bank:7} PCR{int(i):<2} {status:8} predicted {want[:16]}" - + ("" if status == "ok" or got is None else f" read {got[:16]}")) - print("ALL PREDICTED PCRS MATCH" if not bad else f"{bad} PREDICTED PCR(S) DO NOT MATCH") - return bad == 0 - - -def main(): - ap = argparse.ArgumentParser(description="Reproduce stage0's PCRs from its release artifacts") +def write_json(path: str, doc: dict[str, Any]) -> None: + with open(path, "w") as f: + json.dump(doc, f, indent=2) + f.write("\n") + + +def main() -> None: + ap = argparse.ArgumentParser(description="Write stage0's PCR replay file (and reference PCRs)") ap.add_argument("dir", help="stage0 build/ or extracted release directory") - ap.add_argument("--payload-sha256", help="also predict PCR14 for this payload digest") ap.add_argument("--banks", default="sha256,sha384", help="comma-separated (default sha256,sha384)") - ap.add_argument("--out", help="write JSON here (default stdout)") - ap.add_argument("--check", metavar="LOG", help="compare against a test-payload serial log") + ap.add_argument("--replay", required=True, help="write the pcr-replay/v1 file here") + ap.add_argument("--out", help="also write the reference pcrs.json here") a = ap.parse_args() - pred = predict(a.dir, a.banks.split(","), a.payload_sha256) - if a.check: - sys.exit(0 if check(pred, a.check) else 1) - js = json.dumps(pred, indent=2) + "\n" + banks = a.banks.split(",") + rf = replay_file(a.dir, banks) + write_json(a.replay, rf) if a.out: - with open(a.out, "w") as f: - f.write(js) - else: - sys.stdout.write(js) + write_json(a.out, reference_pcrs(rf, banks)) if __name__ == "__main__": From bd5f47c86532d8c987c79f07adf426925fb4d2c5 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:43:16 +0000 Subject: [PATCH 18/21] gvnic: one summary line by default, on stage0's log timeline The driver printed ~25 lines per probe and, as a separate image, had no access to stage0's [ S.mmm] timestamps. Now: - stage0 hands each embedded driver its timestamp epoch (counter value at t = 0 + calibrated cycles/ms, two LE u64) as the image's LoadOptions before start_image; gvnic's clock.rs reads the same free-running counter, so its lines carry stage0's stamp ([ ?.???] if no epoch was passed). - A successful probe prints one line: [ 0.115] gvnic: 1ae0:0042 rev 0, GQI_QPL, 1 tx/1 rx, mtu 1460, mac ..., link up Step-by-step AQ/describe/queue detail moves behind a `verbose` cargo feature (vlog!). Every error path still prints at default, with its detail. Verified on GCP n2d-standard-2 Shielded (gVNIC) and locally on QEMU x86_64. Co-Authored-By: Claude Opus 5.5 --- crates/gvnic/Cargo.toml | 4 ++ crates/gvnic/src/binding.rs | 24 +++--------- crates/gvnic/src/clock.rs | 75 +++++++++++++++++++++++++++++++++++++ crates/gvnic/src/device.rs | 53 ++++++++++++++------------ crates/gvnic/src/main.rs | 12 +++++- crates/gvnic/src/snp.rs | 2 +- crates/stage0/src/net.rs | 25 ++++++++++--- crates/stage0/src/timing.rs | 10 +++++ 8 files changed, 154 insertions(+), 51 deletions(-) create mode 100644 crates/gvnic/src/clock.rs diff --git a/crates/gvnic/Cargo.toml b/crates/gvnic/Cargo.toml index a5874a5..10e48e9 100644 --- a/crates/gvnic/Cargo.toml +++ b/crates/gvnic/Cargo.toml @@ -12,6 +12,10 @@ description = "UEFI SimpleNetworkProtocol driver for the Google Virtual NIC (gVN # the image stays resident. [workspace] +[features] +# Step-by-step probe/AQ logging (clock.rs vlog!); default prints errors + one summary line. +verbose = [] + [dependencies] uefi = { version = "0.35", features = ["alloc", "global_allocator", "panic_handler"] } uefi-raw = "0.11" diff --git a/crates/gvnic/src/binding.rs b/crates/gvnic/src/binding.rs index 1ea9092..110ea3c 100644 --- a/crates/gvnic/src/binding.rs +++ b/crates/gvnic/src/binding.rs @@ -87,43 +87,29 @@ unsafe extern "efiapi" fn start( // the parent bus and directly), so start() is invoked a second time once we // already manage the device. That is benign; only log genuine failures. if e.status() != Status::ALREADY_STARTED { - uefi::println!( - "gvnic: start(): open PciIo BY_DRIVER failed: {:?}", - e.status() - ); + log!("start(): open PciIo BY_DRIVER failed: {:?}", e.status()); } return e.status(); } }; - uefi::println!("gvnic: start(): probing gVNIC device..."); + vlog!("start(): probing gVNIC device..."); // On any error, `pci` drops here and closes the BY_DRIVER open (releasing the device). let nic = match unsafe { crate::device::probe(&pci.0) } { Ok(nic) => nic, Err(e) => { - uefi::println!("gvnic: probe FAILED: {:?}", e); + log!("probe FAILED: {:?}", e); return e; } }; - let mac = nic.mac(); - uefi::println!( - "gvnic: probe OK mac={:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x} mtu={}", - mac[0], - mac[1], - mac[2], - mac[3], - mac[4], - mac[5], - nic.mtu - ); // Keep PciIo open for the device's lifetime (probe stored the raw pointer in `nic`). core::mem::forget(pci); match crate::snp::install(controller, nic) { Ok(()) => { - uefi::println!("gvnic: SNP installed on controller; networking should come up"); + vlog!("SNP installed on controller; networking should come up"); Status::SUCCESS } Err(e) => { - uefi::println!("gvnic: SNP install failed: {:?}", e.status()); + log!("SNP install failed: {:?}", e.status()); e.status() } } diff --git a/crates/gvnic/src/clock.rs b/crates/gvnic/src/clock.rs new file mode 100644 index 0000000..e1d8ade --- /dev/null +++ b/crates/gvnic/src/clock.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Log lines on stage0's timeline: `[ S.mmm] gvnic: ...`, the same stamp as stage0's `slog!`. +//! +//! stage0 passes its epoch as this image's LoadOptions: the free-running cycle counter's value +//! at its t = 0 and its calibrated cycles per millisecond, each a little-endian u64 (stage0 +//! `timing::epoch`). This driver reads the same counter (x86_64 `rdtsc`, aarch64 +//! `cntvct_el0`), so no second calibration. Without an epoch the stamp is `[ ?.???]`. + +use core::sync::atomic::{AtomicU64, Ordering}; + +static START: AtomicU64 = AtomicU64::new(0); +static CYCLES_PER_MS: AtomicU64 = AtomicU64::new(0); + +/// Take the epoch from this image's LoadOptions (16 bytes; anything else leaves it unset). +pub fn init(load_options: Option<&[u8]>) { + if let Some(o) = load_options { + if o.len() == 16 { + let le = |b: &[u8]| u64::from_le_bytes(b.try_into().unwrap_or([0; 8])); + START.store(le(&o[..8]), Ordering::Relaxed); + CYCLES_PER_MS.store(le(&o[8..]), Ordering::Relaxed); + } + } +} + +#[cfg(target_arch = "x86_64")] +#[inline] +fn raw() -> u64 { + // SAFETY: `rdtsc` is unprivileged and always present on x86_64 UEFI hosts. + unsafe { core::arch::x86_64::_rdtsc() } +} + +#[cfg(target_arch = "aarch64")] +#[inline] +fn raw() -> u64 { + let v: u64; + // SAFETY: CNTVCT_EL0 is the EL0-readable virtual counter; the read is side-effect free. + unsafe { core::arch::asm!("mrs {}, cntvct_el0", out(reg) v, options(nomem, nostack)) }; + v +} + +/// The current stamp, formatted like stage0's (`{:>5}.{:03}` seconds). +pub struct Stamp; + +impl core::fmt::Display for Stamp { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let per_ms = CYCLES_PER_MS.load(Ordering::Relaxed); + if per_ms == 0 { + return write!(f, "{:>5}.???", "?"); + } + let ms = raw().wrapping_sub(START.load(Ordering::Relaxed)) / per_ms; + write!(f, "{:>5}.{:03}", ms / 1000, ms % 1000) + } +} + +/// Always printed: errors, and the one-line probe summary. +macro_rules! log { + ($($a:tt)*) => { + uefi::println!("[{}] gvnic: {}", $crate::clock::Stamp, format_args!($($a)*)) + }; +} + +/// Step-by-step detail, compiled in only with the `verbose` feature. +#[cfg(feature = "verbose")] +macro_rules! vlog { + ($($a:tt)*) => { log!($($a)*) }; +} + +/// No-op form; still references the arguments so they don't trip unused warnings. +#[cfg(not(feature = "verbose"))] +macro_rules! vlog { + ($($a:tt)*) => {{ + let _ = format_args!($($a)*); + }}; +} diff --git a/crates/gvnic/src/device.rs b/crates/gvnic/src/device.rs index e14e8a0..2d3b158 100644 --- a/crates/gvnic/src/device.rs +++ b/crates/gvnic/src/device.rs @@ -41,11 +41,6 @@ use uefi::{Event, Status}; use crate::pci::{PciAttrOp, PciIoProtocol, PciMapOp, PciWidth, PCI_ATTR_BUS_MASTER}; -/// `uefi::println!` with a `gvnic:` prefix. -macro_rules! log { - ($($a:tt)*) => { uefi::println!("gvnic: {}", format_args!($($a)*)) }; -} - /// PCI identity (gve.h:26,29: PCI_VENDOR_ID_GOOGLE / PCI_DEV_ID_GVNIC). pub const GVNIC_VENDOR_ID: u16 = 0x1ae0; pub const GVNIC_DEVICE_ID: u16 = 0x0042; @@ -372,7 +367,7 @@ impl AdminQueue { let st = self.exec_status(pci, cmd)?; let opcode = u32::from_be_bytes([cmd[0], cmd[1], cmd[2], cmd[3]]); if st == AQ_PASSED { - log!(" AQ opcode 0x{opcode:x}: PASSED"); + vlog!(" AQ opcode 0x{opcode:x}: PASSED"); Ok(()) } else { log!(" AQ opcode 0x{opcode:x}: status 0x{st:08x}"); @@ -462,7 +457,7 @@ unsafe fn parse_describe(buf: *const u8) -> Result { } let num_opts = get_be16(buf, 30) as usize; let total_len = (get_be16(buf, 32) as usize).clamp(40, PAGE); - log!( + vlog!( " describe: max_reg_pages={} tx_entries={} rx_entries={} default_queues={} mtu={} counters={} tx_pages_per_qpl={} rx_pages_per_qpl={} options={} total_len={}", d.max_registered_pages, d.tx_entries, d.rx_entries, get_be16(buf, 14), d.mtu, d.counters, d.tx_pages_per_qpl, get_be16(buf, 22), num_opts, total_len @@ -486,7 +481,7 @@ unsafe fn parse_describe(buf: *const u8) -> Result { return Err(Status::DEVICE_ERROR); } let mask = if len >= 4 { get_be32(buf, p) } else { 0 }; - log!(" option 0x{id:x} len={len} required_features=0x{req:x} mask=0x{mask:x}"); + vlog!(" option 0x{id:x} len={len} required_features=0x{req:x} mask=0x{mask:x}"); if req == 0 { match id { OPT_GQI_QPL if len >= 4 => gqi_qpl_mask = Some(mask), @@ -511,7 +506,7 @@ unsafe fn parse_describe(buf: *const u8) -> Result { } }; if !other_formats.is_empty() { - log!(" describe: also offered {other_formats:x?}; using GQI_QPL"); + vlog!(" describe: also offered {other_formats:x?}; using GQI_QPL"); } if let (Some(j), true) = (jumbo_mtu, mask & SUP_JUMBO_FRAMES != 0) { d.mtu = j; @@ -664,7 +659,7 @@ impl Gvnic { /// device is reset, so nothing is left doing DMA. pub unsafe fn probe(pci: &PciIoProtocol) -> Result { let rev = cfg_r8(pci, 0x08); - log!("PCI 1ae0:0042 revision {rev}"); + vlog!("PCI 1ae0:0042 revision {rev}"); // Memory decode + bus mastering; INTx disabled (Command bit 10). MSI-X left disabled. let st = (pci.attributes)( @@ -673,7 +668,11 @@ pub unsafe fn probe(pci: &PciIoProtocol) -> Result { PCI_ATTR_MEMORY | PCI_ATTR_BUS_MASTER, core::ptr::null_mut(), ); - log!("memory+bus-master enable: {st:?}"); + if st.is_success() { + vlog!("memory+bus-master enable: {st:?}"); + } else { + log!("memory+bus-master enable: {st:?}"); + } cfg_w16(pci, 0x04, cfg_r16(pci, 0x04) | (1 << 10)); let num_msix = msix_table_size(pci); @@ -685,7 +684,7 @@ pub unsafe fn probe(pci: &PciIoProtocol) -> Result { let max_tx = reg_rd(pci, regs::MAX_TX_QUEUES); let max_rx = reg_rd(pci, regs::MAX_RX_QUEUES); let dev_status = reg_rd(pci, regs::DEVICE_STATUS); - log!("msix={num_msix} ntfy_blks={num_ntfy} max_tx={max_tx} max_rx={max_rx} device_status=0x{dev_status:x}"); + vlog!("msix={num_msix} ntfy_blks={num_ntfy} max_tx={max_tx} max_rx={max_rx} device_status=0x{dev_status:x}"); if max_tx == 0 || max_rx == 0 { return Err(Status::DEVICE_ERROR); } @@ -738,8 +737,8 @@ unsafe fn bring_up( cmd_be64(&mut c, 8, DRIVER_INFO_LEN as u64); cmd_be64(&mut c, 16, info.dev); match aq.exec_status(pci, &c)? { - AQ_PASSED => log!(" verify-driver-compatibility: PASSED"), - AQ_UNIMPLEMENTED => log!(" verify-driver-compatibility: UNIMPLEMENTED (ok)"), + AQ_PASSED => vlog!(" verify-driver-compatibility: PASSED"), + AQ_UNIMPLEMENTED => vlog!(" verify-driver-compatibility: UNIMPLEMENTED (ok)"), s => { log!(" verify-driver-compatibility: status 0x{s:08x}"); return Err(Status::DEVICE_ERROR); @@ -839,7 +838,7 @@ unsafe fn bring_up( cmd_be16(&mut c, 54, BUF as u16); // packet_buffer_size aq.exec(pci, &c)?; let rx_db = get_be32(qres.host, 64); - log!(" queues: tx db={tx_db} counter={tx_ctr} rx db={rx_db}"); + vlog!(" queues: tx db={tx_db} counter={tx_ctr} rx db={rx_db}"); if tx_ctr >= d.counters { log!( " tx counter_index {tx_ctr} out of range ({} counters)", @@ -860,14 +859,6 @@ unsafe fn bring_up( } delay_ms(SLEEP_MS); } - log!( - "link {}", - if link { - "up" - } else { - "NOT up after 5s (continuing)" - } - ); // Stop DMA at ExitBootServices (spec §10.3). Context leaked: lives as long as the event. let ctx = Box::into_raw(Box::new(EbsCtx { pci, rev })); @@ -877,13 +868,27 @@ unsafe fn bring_up( Some(on_exit_boot_services), NonNull::new(ctx.cast()), ) { - Ok(_) => log!("ExitBootServices reset hook armed"), + Ok(_) => vlog!("ExitBootServices reset hook armed"), Err(e) => log!( "ExitBootServices hook FAILED: {:?} (device left running)", e.status() ), } + // The one line a successful probe prints by default (detail: the `verbose` feature). + let m = d.mac; + log!( + "1ae0:0042 rev {rev}, GQI_QPL, 1 tx/1 rx, mtu {}, mac {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}, link {}", + d.mtu, + m[0], + m[1], + m[2], + m[3], + m[4], + m[5], + if link { "up" } else { "NOT up after 5s (continuing)" } + ); + let tx_slots = (d.tx_pages_per_qpl as usize * PAGE / BUF) as u32; let tx_counter = counters.host.add(tx_ctr as usize * 4) as *const u8; Ok(Gvnic { diff --git a/crates/gvnic/src/main.rs b/crates/gvnic/src/main.rs index db54585..1631de4 100644 --- a/crates/gvnic/src/main.rs +++ b/crates/gvnic/src/main.rs @@ -26,27 +26,35 @@ extern crate alloc; +#[macro_use] +mod clock; mod binding; mod device; mod pci; mod snp; +use uefi::boot; use uefi::prelude::*; +use uefi::proto::loaded_image::LoadedImage; #[entry] fn main() -> Status { uefi::helpers::init().unwrap(); + // stage0's log-timestamp epoch, if it passed one (clock.rs). + if let Ok(li) = boot::open_protocol_exclusive::(boot::image_handle()) { + clock::init(li.load_options_as_bytes()); + } // Install the DriverBinding and return SUCCESS. Because the PE subsystem is // EFI_BOOT_SERVICE_DRIVER, the image stays resident after this returns; the // firmware (or stage0's connect_all_controllers) calls back into binding::start // when it connects the gVNIC controller. match binding::install() { Ok(()) => { - uefi::println!("gvnic: DriverBinding installed (idle until a gVNIC device binds)"); + vlog!("DriverBinding installed (idle until a gVNIC device binds)"); Status::SUCCESS } Err(e) => { - uefi::println!("gvnic: failed to install DriverBinding: {:?}", e.status()); + log!("failed to install DriverBinding: {:?}", e.status()); e.status() } } diff --git a/crates/gvnic/src/snp.rs b/crates/gvnic/src/snp.rs index 68fafca..d4fe088 100644 --- a/crates/gvnic/src/snp.rs +++ b/crates/gvnic/src/snp.rs @@ -136,7 +136,7 @@ unsafe extern "efiapi" fn initialize( } d.nic.init_rx(); d.mode.state = NetworkState::INITIALIZED; - uefi::println!("gvnic: SNP initialized (rx posted, link up)"); + vlog!("SNP initialized (rx posted, link up)"); Status::SUCCESS } diff --git a/crates/stage0/src/net.rs b/crates/stage0/src/net.rs index 07ebac9..3736d37 100644 --- a/crates/stage0/src/net.rs +++ b/crates/stage0/src/net.rs @@ -5,8 +5,9 @@ //! assume the interface is addressed. Nothing here is HTTP-specific. use uefi::boot; +use uefi::proto::loaded_image::LoadedImage; use uefi::proto::network::ip4config2::Ip4Config2; -use uefi::Status; +use uefi::{Handle, Status}; use uefi_raw::protocol::network::ip4_config2::Ip4Config2Policy; /// How often to poll for the DHCP lease. Fine-grained so bring-up returns promptly @@ -58,16 +59,30 @@ fn load_embedded_drivers() { "stage0: loading embedded {name} driver ({} bytes)", image.len() ); + // The driver copies the epoch in its entry point, i.e. during start_image, so a local + // buffer outlives its use. + let epoch = crate::timing::epoch(); match crate::secauth::load_image_verified(image) { - Ok(handle) => match boot::start_image(handle) { - Ok(()) => crate::slog!("stage0: {name} driver started"), - Err(e) => crate::slog!("stage0: {name} start_image failed: {:?}", e.status()), - }, + Ok(handle) => { + match set_driver_epoch(handle, &epoch).and_then(|()| boot::start_image(handle)) { + Ok(()) => crate::slog!("stage0: {name} driver started"), + Err(e) => crate::slog!("stage0: {name} start failed: {:?}", e.status()), + } + } Err(status) => crate::slog!("stage0: {name} load_image failed: {status:?}"), } } } +/// Hand a loaded driver image stage0's log-timestamp epoch as its LoadOptions. +fn set_driver_epoch(handle: Handle, epoch: &[u8; 16]) -> uefi::Result { + let mut loaded = boot::open_protocol_exclusive::(handle)?; + // SAFETY: `epoch` outlives the driver's read of it (its entry point, run by the + // start_image that follows; the protocol is closed again when `loaded` drops). + unsafe { loaded.set_load_options(epoch.as_ptr(), epoch.len() as u32) }; + Ok(()) +} + /// Bring the network up: connect the firmware's drivers, then obtain a DHCP lease. /// Call once before any networking. pub fn bringup() -> Result<(), Status> { diff --git a/crates/stage0/src/timing.rs b/crates/stage0/src/timing.rs index 45be359..5c3fa94 100644 --- a/crates/stage0/src/timing.rs +++ b/crates/stage0/src/timing.rs @@ -72,6 +72,16 @@ pub fn since_boot_ms() -> u64 { raw().wrapping_sub(START.load(Ordering::Relaxed)) / per_ms } +/// This timeline's epoch for an embedded driver's `LoadOptions`: the raw counter value at t = 0 +/// and the calibrated cycles per millisecond, each a little-endian u64. The driver reads the +/// same counter, so its log stamps land on stage0's timeline (gvnic `clock.rs`). +pub fn epoch() -> [u8; 16] { + let mut e = [0u8; 16]; + e[..8].copy_from_slice(&START.load(Ordering::Relaxed).to_le_bytes()); + e[8..].copy_from_slice(&CYCLES_PER_MS.load(Ordering::Relaxed).to_le_bytes()); + e +} + /// A `[ S.mmm]`-style stamp (seconds.milliseconds since [`init`]). Returns a /// `Display` wrapper so the [`slog!`](crate::slog) macro formats without allocating. pub fn stamp() -> Stamp { From 615b8103f3b44fc88b1cab174111bbe4a1167b3b Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:23:56 +0000 Subject: [PATCH 19/21] gvnic: direct BAR2 doorbells; full device teardown at ExitBootServices Doorbells: BAR2 (queue doorbells) is now written with direct big-endian stores to the BAR's host address (PciIo.GetBarAttributes; host = AddrRangeMin - AddrTranslationOffset), as every reference driver does (Linux iowrite32be, FreeBSD bus_write_4, DPDK rte_write32, iPXE's EFI build writel). BAR0 (registers, admin queue) stays on PciIo.Mem. GCE backs the doorbell BAR as memory rather than trapping MMIO: under Intel TDX the firmware's PciIo.Mem path is a TDVMCALL MMIO hypercall that never reaches it (doorbells read back 0, the device never sees TX or RX posts), while a direct store through the firmware's shared MMIO mapping does. Device-supplied doorbell indices are bounds-checked against the BAR length, since the address is now dereferenced directly. Teardown: the ExitBootServices hook now does what Linux does on close + remove instead of only a reset: DESTROY_TX_QUEUE, DESTROY_RX_QUEUE, UNREGISTER_PAGE_LIST (TX, RX), DECONFIGURE_DEVICE_RESOURCES, then reset (a failed command surrenders to the reset, as gve_close does). Admin-queue commands use pre-allocated DMA memory and Stall-based polling only, as EBS requires. The hook is armed once the device has its fixed home in the SNP instance. Verified: GCP c3 TDX (where gVNIC had no working data path before), c3 Shielded and n2d SEV-SNP; QEMU x86_64 / aarch64 (no gVNIC there; the driver stays idle). Co-Authored-By: Claude Opus 5.5 --- crates/gvnic/src/device.rs | 146 ++++++++++++++++++++++++++++--------- crates/gvnic/src/pci.rs | 11 ++- crates/gvnic/src/snp.rs | 2 + 3 files changed, 124 insertions(+), 35 deletions(-) diff --git a/crates/gvnic/src/device.rs b/crates/gvnic/src/device.rs index 2d3b158..4a742f5 100644 --- a/crates/gvnic/src/device.rs +++ b/crates/gvnic/src/device.rs @@ -12,6 +12,13 @@ //! interrupts), no offloads, no RSS. Everything device-facing is BIG-endian: BAR0 //! registers, admin-queue commands, descriptors, doorbells, event counters. //! +//! BAR0 (registers) goes through `PciIo.Mem`; BAR2 (queue doorbells) is written with direct +//! stores to the BAR's host address, as every reference driver does (Linux iowrite32be, +//! FreeBSD bus_write_4, DPDK rte_write32, iPXE's EFI build writel). GCE backs the doorbell BAR +//! as memory rather than trapping MMIO: under Intel TDX the firmware's `PciIo.Mem` path is a +//! TDVMCALL MMIO hypercall that never reaches it (writes dropped, reads 0), while a direct store +//! through the firmware's shared MMIO mapping does. +//! //! Flow (probe): PCI enable -> version string -> register admin queue (by PCI revision) -> //! VERIFY_DRIVER_COMPATIBILITY -> DESCRIBE_DEVICE (+ option TLVs) -> //! CONFIGURE_DEVICE_RESOURCES -> allocate rings + QPLs -> REGISTER_PAGE_LIST (TX, RX) -> @@ -29,7 +36,6 @@ // few protocol constants are kept for reference. #![allow(dead_code)] -use alloc::boxed::Box; use alloc::vec; use alloc::vec::Vec; use core::ffi::c_void; @@ -78,6 +84,12 @@ const OP_CONFIGURE_DEVICE_RESOURCES: u32 = 0x2; const OP_REGISTER_PAGE_LIST: u32 = 0x3; const OP_CREATE_TX_QUEUE: u32 = 0x5; const OP_CREATE_RX_QUEUE: u32 = 0x6; +const OP_UNREGISTER_PAGE_LIST: u32 = 0x4; +const OP_DESTROY_TX_QUEUE: u32 = 0x7; +const OP_DESTROY_RX_QUEUE: u32 = 0x8; +const OP_DECONFIGURE_DEVICE_RESOURCES: u32 = 0x9; +/// TX QPL id (Linux's: TX QPLs are numbered from 0). +const TX_QPL_ID: u32 = 0; const OP_VERIFY_DRIVER_COMPATIBILITY: u32 = 0xf; /// Admin status codes (gve_adminq.h:47-66). @@ -222,9 +234,34 @@ unsafe fn reg_wr(pci: &PciIoProtocol, off: u64, v: u32) { } /// Ring doorbell `db_index` (BAR2 + 4*db_index) with a free-running count. Release fence /// first, so every descriptor/payload store is visible before the device is told. -unsafe fn doorbell(pci: &PciIoProtocol, db_index: u32, value: u32) { +unsafe fn doorbell(db: *mut u8, db_index: u32, value: u32) { fence(Ordering::Release); - mmio_write32(pci, DB_BAR, 4 * db_index as u64, value); + (db.add(4 * db_index as usize) as *mut u32).write_volatile(value.to_be()); +} + +/// Host address and length of memory BAR `bar`, from `PciIo.GetBarAttributes` (its first +/// memory descriptor; host = AddrRangeMin - AddrTranslationOffset, EDK2 TO_HOST_ADDRESS). +unsafe fn bar_host_range(pci: &PciIoProtocol, bar: u8) -> Result<(u64, u64), Status> { + let mut res: *mut c_void = core::ptr::null_mut(); + let st = (pci.get_bar_attributes)(pci, bar, core::ptr::null_mut(), &mut res); + if !st.is_success() || res.is_null() { + log!("GetBarAttributes(bar{bar}) failed: {st:?}"); + return Err(if st.is_success() { + Status::DEVICE_ERROR + } else { + st + }); + } + // ACPI QWORD address-space descriptor (0x8A): ResType @3, AddrRangeMin @14, + // AddrTranslationOffset @30, AddrLen @38 (packed). + let p = res as *const u8; + let rd = |o: usize| (p.add(o) as *const u64).read_unaligned(); + let found = (*p == 0x8a && *p.add(3) == 0).then(|| (rd(14).wrapping_sub(rd(30)), rd(38))); + let _ = boot::free_pool(NonNull::new_unchecked(res as *mut u8)); + found.ok_or_else(|| { + log!("bar{bar}: no memory descriptor"); + Status::DEVICE_ERROR + }) } unsafe fn cfg_r8(pci: &PciIoProtocol, off: u32) -> u8 { @@ -414,17 +451,34 @@ unsafe fn reset(pci: &PciIoProtocol, rev: u8) -> bool { // ---- ExitBootServices: stop DMA before the OS owns the memory --------------------------- -struct EbsCtx { - pci: *const PciIoProtocol, - rev: u8, -} - -/// Reset the device at ExitBootServices (spec §10.3): RX buffers are posted into -/// boot-services memory the OS is about to reuse. No logging here (console may be gone). +/// Tear the device down at ExitBootServices, as Linux does on close + remove (gve_close -> +/// gve_destroy_rings + gve_unregister_qpls, gve_teardown_device_resources, gve_adminq_release): +/// destroy the queues, unregister both page lists, deconfigure the device resources, then reset. +/// The device must let go of every page it was given before the firmware IOMMU's own EBS +/// handler (TPL_CALLBACK, after this one at TPL_NOTIFY) converts them back to private memory -- +/// RX buffers are posted into boot-services memory the OS is about to reuse. Admin-queue commands +/// use pre-allocated DMA memory and Stall-based polling only (no allocation, as EBS requires). A +/// failed command surrenders to the reset, as gve_close does. No logging (console may be gone). unsafe extern "efiapi" fn on_exit_boot_services(_e: Event, ctx: Option>) { if let Some(c) = ctx { - let c = &*(c.as_ptr() as *const EbsCtx); - let _ = reset(&*c.pci, c.rev); + (*(c.as_ptr() as *mut Gvnic)).teardown(); + } +} + +/// Arm the ExitBootServices teardown for `nic`, which must stay at this address (the SNP +/// device it lives in is leaked) for the life of boot services. +pub unsafe fn arm_exit_boot_services(nic: *mut Gvnic) { + match boot::create_event( + EventType::SIGNAL_EXIT_BOOT_SERVICES, + Tpl::NOTIFY, + Some(on_exit_boot_services), + NonNull::new(nic.cast()), + ) { + Ok(_) => vlog!("ExitBootServices teardown armed"), + Err(e) => log!( + "ExitBootServices hook FAILED: {:?} (device left running)", + e.status() + ), } } @@ -543,6 +597,10 @@ struct Rx { /// A bound gVNIC: one TX + one RX GQI-QPL queue, polled. pub struct Gvnic { pci: *const PciIoProtocol, + /// Host address of BAR2 (doorbells), written directly (see the module docs). + db: *mut u8, + /// RX QPL id (TX is [`TX_QPL_ID`]), for unregistering at teardown. + rx_qpl_id: u32, /// Device MTU (L3 payload; GCP default 1460), capped so a frame fits one 2 KiB buffer. pub mtu: u32, mac: [u8; 6], @@ -560,6 +618,28 @@ impl Gvnic { self.mac } + /// Release everything the device holds, then reset it (see [`on_exit_boot_services`]). + unsafe fn teardown(&mut self) { + let pci = &*self.pci; + let steps: [(u32, Option); 5] = [ + (OP_DESTROY_TX_QUEUE, Some(0)), + (OP_DESTROY_RX_QUEUE, Some(0)), + (OP_UNREGISTER_PAGE_LIST, Some(TX_QPL_ID)), + (OP_UNREGISTER_PAGE_LIST, Some(self.rx_qpl_id)), + (OP_DECONFIGURE_DEVICE_RESOURCES, None), + ]; + for (op, id) in steps { + let mut c = cmd_new(op); + if let Some(id) = id { + cmd_be32(&mut c, 8, id); + } + if self.aq.exec(pci, &c).is_err() { + break; // surrender to the reset (gve_close) + } + } + let _ = reset(pci, self.rev); + } + /// RX is fully posted at probe (the data ring must be prefilled before CREATE_RX_QUEUE, /// spec §4.7), so SNP Initialize has nothing to do here. pub unsafe fn init_rx(&mut self) {} @@ -567,7 +647,7 @@ impl Gvnic { /// Copy one received frame into `out` (capacity `cap`); `None` if nothing is pending. /// Errored, multi-fragment, or oversized frames are consumed and dropped. pub unsafe fn receive(&mut self, out: *mut u8, cap: usize) -> Option { - let pci = &*self.pci; + let db = self.db; let rx = &mut self.rx; loop { let idx = (rx.cnt % rx.entries) as usize; @@ -596,7 +676,7 @@ impl Gvnic { rx.cnt = rx.cnt.wrapping_add(1); rx.seq = if rx.seq == 7 { 1 } else { rx.seq + 1 }; rx.fill = rx.fill.wrapping_add(1); - doorbell(pci, rx.db_index, rx.fill); + doorbell(db, rx.db_index, rx.fill); if got.is_some() { return got; } @@ -611,7 +691,6 @@ impl Gvnic { len: usize, caller: *const c_void, ) -> Result<(), Status> { - let pci = &*self.pci; let tx = &mut self.tx; if len == 0 || len > self.mtu as usize + ETH_HLEN { return Err(Status::INVALID_PARAMETER); @@ -635,7 +714,7 @@ impl Gvnic { put_be64(d, 8, qpl_off as u64); tx.callers[slot] = caller; tx.req = tx.req.wrapping_add(1); - doorbell(pci, tx.db_index, tx.req); + doorbell(self.db, tx.db_index, tx.req); Ok(()) } @@ -693,6 +772,9 @@ pub unsafe fn probe(pci: &PciIoProtocol) -> Result { mmio_write8(pci, REG_BAR, regs::DRIVER_VERSION, *b); } + // Before the admin queue exists, so a failure here leaves nothing to reset. + let (db_base, db_len) = bar_host_range(pci, DB_BAR)?; + let aq_dma = Dma::alloc(pci, PAGE)?; register_adminq(pci, rev, &aq_dma); let ec = reg_rd(pci, regs::ADMINQ_EVENT_COUNTER); @@ -704,7 +786,7 @@ pub unsafe fn probe(pci: &PciIoProtocol) -> Result { prod: ec, }; - match bring_up(pci, rev, num_ntfy, max_tx, aq) { + match bring_up(pci, rev, num_ntfy, max_tx, aq, db_base as *mut u8, db_len) { Ok(nic) => Ok(nic), Err(e) => { let ok = reset(pci, rev); @@ -724,6 +806,8 @@ unsafe fn bring_up( num_ntfy: u32, max_tx: u32, mut aq: AdminQueue, + db: *mut u8, + db_len: u64, ) -> Result { // VERIFY_DRIVER_COMPATIBILITY (spec §4.1): PASSED or UNIMPLEMENTED both fine. let info = Dma::alloc(pci, DRIVER_INFO_LEN)?; @@ -795,7 +879,7 @@ unsafe fn bring_up( } // REGISTER_PAGE_LIST (spec §4.5): TX id 0, RX id min(max_tx, ntfy/2) (Linux's values). - let tx_qpl_id = 0u32; + let tx_qpl_id = TX_QPL_ID; let rx_qpl_id = max_tx.min(num_ntfy / 2); for (id, qpl, pages) in [ (tx_qpl_id, &tx_qpl, d.tx_pages_per_qpl), @@ -846,9 +930,16 @@ unsafe fn bring_up( ); return Err(Status::DEVICE_ERROR); } + // The doorbells are written through a raw pointer: keep the device's indices inside BAR2. + for (q, idx) in [("tx", tx_db), ("rx", rx_db)] { + if 4 * idx as u64 + 4 > db_len { + log!(" {q} doorbell index {idx} outside BAR2 ({db_len} bytes)"); + return Err(Status::DEVICE_ERROR); + } + } // Post every RX slot (spec §7.2 step 6). - doorbell(pci, rx_db, d.rx_entries); + doorbell(db, rx_db, d.rx_entries); // Link (spec §2.5): Linux does not wait; we poll briefly and log. let mut link = false; @@ -860,21 +951,6 @@ unsafe fn bring_up( delay_ms(SLEEP_MS); } - // Stop DMA at ExitBootServices (spec §10.3). Context leaked: lives as long as the event. - let ctx = Box::into_raw(Box::new(EbsCtx { pci, rev })); - match boot::create_event( - EventType::SIGNAL_EXIT_BOOT_SERVICES, - Tpl::NOTIFY, - Some(on_exit_boot_services), - NonNull::new(ctx.cast()), - ) { - Ok(_) => vlog!("ExitBootServices reset hook armed"), - Err(e) => log!( - "ExitBootServices hook FAILED: {:?} (device left running)", - e.status() - ), - } - // The one line a successful probe prints by default (detail: the `verbose` feature). let m = d.mac; log!( @@ -893,6 +969,8 @@ unsafe fn bring_up( let tx_counter = counters.host.add(tx_ctr as usize * 4) as *const u8; Ok(Gvnic { pci, + db, + rx_qpl_id, mtu, mac: d.mac, rev, diff --git a/crates/gvnic/src/pci.rs b/crates/gvnic/src/pci.rs index 6c0cdc9..840ea39 100644 --- a/crates/gvnic/src/pci.rs +++ b/crates/gvnic/src/pci.rs @@ -94,6 +94,15 @@ type FreeBufferFn = unsafe extern "efiapi" fn( host_address: *mut c_void, ) -> Status; +/// `GetBarAttributes(This, BarIndex, Supports, Resources)`: `*Resources` is a pool buffer of ACPI +/// address-space descriptors (end tag 0x79) that the caller frees. +pub type GetBarAttributesFn = unsafe extern "efiapi" fn( + this: *const PciIoProtocol, + bar_index: u8, + supports: *mut u64, + resources: *mut *mut c_void, +) -> Status; + type AttributesFn = unsafe extern "efiapi" fn( this: *const PciIoProtocol, operation: PciAttrOp, @@ -130,7 +139,7 @@ pub struct PciIoProtocol { flush: usize, get_location: usize, pub attributes: AttributesFn, - get_bar_attributes: usize, + pub get_bar_attributes: GetBarAttributesFn, set_bar_attributes: usize, pub rom_size: u64, pub rom_image: *mut c_void, diff --git a/crates/gvnic/src/snp.rs b/crates/gvnic/src/snp.rs index d4fe088..7f0cd44 100644 --- a/crates/gvnic/src/snp.rs +++ b/crates/gvnic/src/snp.rs @@ -75,6 +75,8 @@ pub fn install(controller: Handle, nic: Gvnic) -> uefi::Result<()> { &SNP_GUID, (&(*p).snp as *const SimpleNetworkProtocol).cast(), )?; + // The device now has a fixed home: arm its ExitBootServices teardown. + crate::device::arm_exit_boot_services(&mut (*p).nic); } Ok(()) } From 34dbc6978a2e32085772d8af692362a7ce7e9b91 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:23:56 +0000 Subject: [PATCH 20/21] stage0: supply a local-APIC timer tick when the firmware's never arrives (GCE TDX) GCE's firmware (ovmf_x64_csm) drives the UEFI tick from the 8254 PIT through the 8259 PIC. An Intel TDX guest receives interrupts only through its virtual x2APIC, so IRQ0 is never delivered: the PIT counts but no UEFI timer event ever fires, and EDK2's network stack (MNP receive polling, DHCP retransmits, TCP timers) never runs. Measured on c3-standard-4: 0 ticks of a 10 ms event in 300 ms under TDX, 30 on Shielded; the firmware's LAPIC timer is masked on both. lapic_tick::ensure() (x86_64, right after timing::init) probes the firmware tick for 50 ms and, only if it is dead, does what OVMF's LocalApicTimerDxe would: calibrates the LAPIC timer against a stall, programs it periodic at the firmware timer's own period on the first free vector, and from its interrupt calls the firmware timer driver's GenerateSoftInterrupt() (one CoreTimerTick per period). The ISR follows LocalApicTimerDxe's structure, including a port of OVMF's NestedInterruptTplLib (BSD-2-Clause-Patent, Fen Systems Ltd.) so a burst of ticks cannot nest RestoreTPL() frames without bound. The LAPIC timer registers are saved and restored exactly at ExitBootServices. Where the firmware tick works (QEMU, Shielded, SEV, SEV-SNP) nothing changes beyond the 50 ms probe. Verified: GCP c3 TDX full chain (22 MB UKI download under the LAPIC tick, stage1, stage2); c3 Shielded and n2d SEV-SNP (tick alive, workaround off); QEMU x86_64 / aarch64 full chains. Co-Authored-By: Claude Opus 5.5 --- crates/stage0/src/lapic_tick.rs | 348 ++++++++++++++++++++++++++++++++ crates/stage0/src/main.rs | 6 + 2 files changed, 354 insertions(+) create mode 100644 crates/stage0/src/lapic_tick.rs diff --git a/crates/stage0/src/lapic_tick.rs b/crates/stage0/src/lapic_tick.rs new file mode 100644 index 0000000..b1bd2c2 --- /dev/null +++ b/crates/stage0/src/lapic_tick.rs @@ -0,0 +1,348 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! A local-APIC timer tick for firmware whose own tick never arrives. +//! +//! GCE's firmware (the `ovmf_x64_csm` family) drives the UEFI tick from the 8254 PIT through +//! the 8259 PIC (OVMF `8254TimerDxe`; upstream OVMF moved every build to `LocalApicTimerDxe` +//! in 89bd992b1f). An Intel TDX guest receives interrupts only through its virtual x2APIC, so +//! IRQ0 is never delivered: the PIT counts, but no timer event ever fires -- and EDK2's network +//! stack (MNP receive polling, DHCP retransmits, TCP timers) runs on timer events. Measured on +//! GCE c3-standard-4: 0 ticks of a 10 ms periodic event in 300 ms under TDX, 30 on Shielded. +//! +//! [`ensure`] checks whether the firmware tick is alive and, only if it is dead, does what +//! `LocalApicTimerDxe` would: program the local APIC timer periodic at the firmware's own +//! timer period on a free vector, and from its interrupt call the firmware timer driver's +//! `GenerateSoftInterrupt()`, which runs the registered tick handler (`CoreTimerTick`) for one +//! period. The firmware's tick bookkeeping is untouched; it just gets its interrupts. The +//! LAPIC timer is masked again at ExitBootServices, so the OS starts with it as it was. +//! +//! The interrupt handler follows `LocalApicTimerDxe`'s structure, including its use of OVMF's +//! NestedInterruptTplLib (ported below as [`nested_raise_tpl`] / [`nested_restore_tpl`]): +//! RestoreTPL() re-enables interrupts while it dispatches event notifications, so a burst of +//! ticks arriving just as an outer RestoreTPL() finishes would otherwise nest without bound and +//! exhaust the stack. + +use core::arch::asm; +use core::ffi::c_void; +use core::ptr::{self, NonNull}; +use core::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}; + +use uefi::boot::{self, EventType, OpenProtocolAttributes, OpenProtocolParams, Tpl}; +use uefi::proto::unsafe_protocol; +use uefi::{Event, Status}; +use uefi_raw::table::boot::Tpl as RawTpl; + +/// `EFI_TIMER_ARCH_PROTOCOL` (PI spec vol. 2). +#[repr(C)] +struct TimerArchProtocol { + register_handler: usize, + set_timer_period: usize, + get_timer_period: unsafe extern "efiapi" fn(*mut TimerArchProtocol, *mut u64) -> Status, + generate_soft_interrupt: unsafe extern "efiapi" fn(*mut TimerArchProtocol) -> Status, +} + +/// `EFI_CPU_INTERRUPT_HANDLER`: (interrupt type, EFI_SYSTEM_CONTEXT -- a pointer union). +type InterruptHandler = unsafe extern "efiapi" fn(isize, *mut c_void); + +/// `EFI_CPU_ARCH_PROTOCOL` (PI spec vol. 2), up to the member used. +#[repr(C)] +struct CpuArchProtocol { + flush_data_cache: usize, + enable_interrupt: usize, + disable_interrupt: usize, + get_interrupt_state: usize, + init: usize, + register_interrupt_handler: + unsafe extern "efiapi" fn(*mut CpuArchProtocol, isize, Option) -> Status, +} + +#[unsafe_protocol("26baccb3-6f42-11d4-bce7-0080c73c8881")] +struct TimerArch(TimerArchProtocol); + +#[unsafe_protocol("26baccb1-6f42-11d4-bce7-0080c73c8881")] +struct CpuArch(CpuArchProtocol); + +/// Vectors tried for the tick, first free one wins (RegisterInterruptHandler refuses a vector +/// that already has a handler, e.g. the 8259's 0x68..0x77). +const VECTORS: core::ops::RangeInclusive = 0x40..=0xef; + +/// How long the liveness probe waits for one firmware tick. +const PROBE_MS: usize = 50; + +// x2APIC MSRs (Intel SDM vol. 3 10.12.1.2) and their xAPIC MMIO offsets (MSR - 0x800) << 4. +const APIC_BASE_MSR: u32 = 0x1b; +const X2APIC_ENABLE: u64 = 1 << 10; +const REG_EOI: u32 = 0x80b; +const REG_LVT_TIMER: u32 = 0x832; +const REG_INIT_COUNT: u32 = 0x838; +const REG_CUR_COUNT: u32 = 0x839; +const REG_DIVIDE: u32 = 0x83e; +const LVT_MASKED: u32 = 1 << 16; +const LVT_PERIODIC: u32 = 1 << 17; +const DIVIDE_BY_1: u32 = 0b1011; + +/// The timer arch protocol the ISR ticks, and the xAPIC MMIO base (null in x2APIC mode). +static TIMER: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +/// The LAPIC timer registers as the firmware left them, restored at ExitBootServices: +/// LVT timer, initial count, divide configuration. +static SAVED_LVT: AtomicU32 = AtomicU32::new(0); +static SAVED_INIT: AtomicU32 = AtomicU32::new(0); +static SAVED_DIVIDE: AtomicU32 = AtomicU32::new(0); +static ENGAGED: AtomicBool = AtomicBool::new(false); +static XAPIC_MMIO: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +static PROBE_TICKS: AtomicU32 = AtomicU32::new(0); + +unsafe fn rdmsr(msr: u32) -> u64 { + let (lo, hi): (u32, u32); + asm!("rdmsr", in("ecx") msr, out("eax") lo, out("edx") hi, options(nomem, nostack)); + ((hi as u64) << 32) | lo as u64 +} + +unsafe fn wrmsr(msr: u32, v: u64) { + asm!("wrmsr", in("ecx") msr, in("eax") v as u32, in("edx") (v >> 32) as u32, + options(nomem, nostack)); +} + +unsafe fn apic_read(reg: u32) -> u32 { + let mmio = XAPIC_MMIO.load(Ordering::Relaxed); + if mmio.is_null() { + rdmsr(reg) as u32 + } else { + (mmio.add(((reg - 0x800) << 4) as usize) as *const u32).read_volatile() + } +} + +unsafe fn apic_write(reg: u32, v: u32) { + let mmio = XAPIC_MMIO.load(Ordering::Relaxed); + if mmio.is_null() { + wrmsr(reg, v as u64) + } else { + (mmio.add(((reg - 0x800) << 4) as usize) as *mut u32).write_volatile(v) + } +} + +unsafe extern "efiapi" fn probe_tick(_e: Event, _c: Option>) { + PROBE_TICKS.fetch_add(1, Ordering::Relaxed); +} + +/// Count firmware timer ticks of a 10 ms periodic event over `ms` milliseconds of stall. +fn ticks_in(ms: usize) -> Option { + let ev = unsafe { + boot::create_event( + EventType::TIMER | EventType::NOTIFY_SIGNAL, + Tpl::CALLBACK, + Some(probe_tick), + None, + ) + } + .ok()?; + let start = PROBE_TICKS.load(Ordering::Relaxed); + let armed = boot::set_timer(&ev, boot::TimerTrigger::Periodic(100_000)).is_ok(); + boot::stall(ms * 1000); + let n = PROBE_TICKS.load(Ordering::Relaxed).wrapping_sub(start); + let _ = boot::close_event(ev); + armed.then_some(n) +} + +// ---- NestedInterruptTplLib, ported -------------------------------------------------------- +// From EDK2 OvmfPkg/Library/NestedInterruptTplLib (Tpl.c, Iret.c), Copyright (C) 2022, Fen +// Systems Ltd., SPDX-License-Identifier: BSD-2-Clause-Patent. Same algorithm; the shared state +// (NESTED_INTERRUPT_STATE) is only touched with interrupts disabled on the boot CPU. + +/// `IsrState->InProgressRestoreTPL` / `IsrState->DeferredRestoreTPL`. +static IN_PROGRESS_RESTORE_TPL: AtomicUsize = AtomicUsize::new(0); +static DEFERRED_RESTORE_TPL: AtomicBool = AtomicBool::new(false); + +/// The prefix of `EFI_SYSTEM_CONTEXT_X64` up to `Rflags` (MdePkg Protocol/DebugSupport.h). +#[repr(C)] +struct SystemContextX64 { + exception_data: u64, + fx_save_state: [u8; 512], + dr: [u64; 6], // Dr0-3, Dr6, Dr7 + cr: [u64; 6], // Cr0-4, Cr8 + rflags: u64, +} +const RFLAGS_IF: u64 = 1 << 9; + +unsafe fn boot_services() -> *mut uefi_raw::table::boot::BootServices { + match uefi::table::system_table_raw() { + Some(st) => (*st.as_ptr()).boot_services, + None => ptr::null_mut(), + } +} + +/// `NestedInterruptRaiseTPL`: raise to TPL_HIGH_LEVEL from inside an interrupt handler +/// (interrupts are already disabled); returns the TPL the interrupt occurred at. +unsafe fn nested_raise_tpl(bs: *mut uefi_raw::table::boot::BootServices) -> RawTpl { + ((*bs).raise_tpl)(RawTpl::HIGH_LEVEL) +} + +/// `NestedInterruptRestoreTPL`: lower back to `interrupted`, deferring to an outer instance of +/// this handler when that is the only way to avoid an unbounded stack of RestoreTPL() frames. +unsafe fn nested_restore_tpl( + bs: *mut uefi_raw::table::boot::BootServices, + interrupted: RawTpl, + ctx: *mut SystemContextX64, +) { + // The interrupt hit an outer handler's RestoreTPL() at the point it had finished + // dispatching (same TPL): return still at TPL_HIGH_LEVEL with interrupts disabled, and let + // that outer handler perform the RestoreTPL() (the "DEFERRAL INVOCATION POINT"). + if interrupted.0 == IN_PROGRESS_RESTORE_TPL.load(Ordering::Relaxed) { + DEFERRED_RESTORE_TPL.store(true, Ordering::Relaxed); + (*ctx).rflags &= !RFLAGS_IF; // DisableInterruptsOnIret + return; + } + // Otherwise the outer RestoreTPL() (if any) is still dispatching at a lower TPL: restore here, + // as often as inner handlers defer to us. Bounded by the number of distinct TPLs. + loop { + let saved = IN_PROGRESS_RESTORE_TPL.swap(interrupted.0, Ordering::Relaxed); + ((*bs).restore_tpl)(interrupted); // re-enables interrupts below TPL_HIGH_LEVEL + asm!("cli", options(nomem, nostack)); + // DEFERRAL RETURN POINT + IN_PROGRESS_RESTORE_TPL.store(saved, Ordering::Relaxed); + if !DEFERRED_RESTORE_TPL.swap(false, Ordering::Relaxed) { + return; + } + } +} + +/// The LAPIC timer interrupt, shaped like `LocalApicTimerDxe`'s TimerInterruptHandler: raise +/// to TPL_HIGH_LEVEL, EOI, one firmware tick (GenerateSoftInterrupt raises/restores HIGH->HIGH, +/// so it dispatches nothing itself), then the nested-safe restore that dispatches events. +unsafe extern "efiapi" fn on_tick(_vector: isize, ctx: *mut c_void) { + let bs = boot_services(); + if bs.is_null() { + apic_write(REG_EOI, 0); + return; + } + let interrupted = nested_raise_tpl(bs); + apic_write(REG_EOI, 0); + let t = TIMER.load(Ordering::Acquire); + if !t.is_null() { + let _ = ((*t).generate_soft_interrupt)(t); + } + nested_restore_tpl(bs, interrupted, ctx as *mut SystemContextX64); +} + +/// Put the LAPIC timer back before the OS takes over. +unsafe extern "efiapi" fn on_exit_boot_services(_e: Event, _c: Option>) { + restore_lapic(); +} + +/// Stop our tick and put the LAPIC timer registers back exactly as the firmware left them. +unsafe fn restore_lapic() { + if !ENGAGED.swap(false, Ordering::AcqRel) { + return; + } + apic_write(REG_LVT_TIMER, LVT_MASKED); // stop interrupts first + apic_write(REG_DIVIDE, SAVED_DIVIDE.load(Ordering::Relaxed)); + apic_write(REG_LVT_TIMER, SAVED_LVT.load(Ordering::Relaxed)); + apic_write(REG_INIT_COUNT, SAVED_INIT.load(Ordering::Relaxed)); +} + +fn open() -> Option> { + let handle = boot::get_handle_for_protocol::

().ok()?; + unsafe { + boot::open_protocol::

( + OpenProtocolParams { + handle, + agent: boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } + .ok() +} + +/// Make sure the UEFI timer ticks: a no-op when the firmware's own tick is alive, otherwise +/// supply one from the local APIC timer. Call once, early (before anything event-driven). +pub fn ensure() { + match ticks_in(PROBE_MS) { + Some(n) if n > 0 => return, + Some(_) => {} + None => { + crate::slog!("stage0: timer: cannot probe the firmware tick (create/set_timer failed)"); + return; + } + } + match unsafe { install() } { + Ok(msg) => { + let n = ticks_in(PROBE_MS).unwrap_or(0); + crate::slog!("stage0: timer: firmware tick dead; {msg}: {n} ticks in {PROBE_MS} ms"); + } + Err(why) => crate::slog!("stage0: timer: firmware tick dead and no LAPIC tick: {why}"), + } +} + +unsafe fn install() -> Result { + let mut timer = open::().ok_or("no EFI_TIMER_ARCH_PROTOCOL")?; + let mut cpu = open::().ok_or("no EFI_CPU_ARCH_PROTOCOL")?; + let timer_p: *mut TimerArchProtocol = &mut timer.0; + let cpu_p: *mut CpuArchProtocol = &mut cpu.0; + + // The firmware's tick period (100 ns units); each GenerateSoftInterrupt advances it by this. + let mut period: u64 = 0; + if !((*timer_p).get_timer_period)(timer_p, &mut period).is_success() || period == 0 { + return Err("firmware timer period unavailable or 0"); + } + + let base = rdmsr(APIC_BASE_MSR); + if base & X2APIC_ENABLE == 0 { + XAPIC_MMIO.store((base & 0xffff_f000) as *mut u8, Ordering::Relaxed); + } + + SAVED_LVT.store(apic_read(REG_LVT_TIMER), Ordering::Relaxed); + SAVED_INIT.store(apic_read(REG_INIT_COUNT), Ordering::Relaxed); + SAVED_DIVIDE.store(apic_read(REG_DIVIDE), Ordering::Relaxed); + ENGAGED.store(true, Ordering::Release); + + // Calibrate the LAPIC timer (divide by 1, masked one-shot) against a 10 ms stall. + apic_write(REG_DIVIDE, DIVIDE_BY_1); + apic_write(REG_LVT_TIMER, LVT_MASKED); + apic_write(REG_INIT_COUNT, u32::MAX); + boot::stall(10_000); + let per_10ms = u32::MAX - apic_read(REG_CUR_COUNT); + apic_write(REG_INIT_COUNT, 0); + if per_10ms == 0 { + restore_lapic(); + return Err("LAPIC timer does not count"); + } + let count = (per_10ms as u64 * period / 100_000).clamp(1, u32::MAX as u64) as u32; + + // Arm the ExitBootServices mask before the tick can run. + boot::create_event( + EventType::SIGNAL_EXIT_BOOT_SERVICES, + Tpl::NOTIFY, + Some(on_exit_boot_services), + None, + ) + .map_err(|_| { + restore_lapic(); + "cannot create the ExitBootServices event" + })?; + + TIMER.store(timer_p, Ordering::Release); + let vector = VECTORS + .clone() + .find(|&v| ((*cpu_p).register_interrupt_handler)(cpu_p, v, Some(on_tick)).is_success()) + .ok_or_else(|| { + restore_lapic(); + "no free interrupt vector" + })?; + apic_write(REG_LVT_TIMER, LVT_PERIODIC | vector as u32); + apic_write(REG_INIT_COUNT, count); + + // Both are architectural protocols that live as long as boot services; keep them open. + core::mem::forget(timer); + core::mem::forget(cpu); + Ok(alloc::format!( + "LAPIC tick on vector {vector:#x} ({}, {count} counts per {} us)", + if XAPIC_MMIO.load(Ordering::Relaxed).is_null() { + "x2APIC" + } else { + "xAPIC" + }, + period / 10 + )) +} diff --git a/crates/stage0/src/main.rs b/crates/stage0/src/main.rs index 367f2c1..58befd6 100644 --- a/crates/stage0/src/main.rs +++ b/crates/stage0/src/main.rs @@ -24,6 +24,8 @@ mod config; mod dns4; mod embedded; mod http; +#[cfg(target_arch = "x86_64")] +mod lapic_tick; mod metadata; mod net; mod secauth; @@ -85,6 +87,10 @@ fn run() -> Result<(), Status> { // Calibrate the boot-relative clock first so every log line below is stamped. timing::init(); crate::slog!("stage0: version: {}", env!("CARGO_PKG_VERSION")); + // Before anything event-driven (the network stack runs on timer events): supply a LAPIC tick + // if the firmware's own never arrives (GCE's PIT-driven firmware under Intel TDX). + #[cfg(target_arch = "x86_64")] + lapic_tick::ensure(); // Fail closed unless the platform is in the state the attestation model assumes: UEFI Secure // Boot enforcing -- SecureBoot on, not in Setup Mode, not in Audit Mode. User and Deployed Mode From 83226296057d0a7058432e5c507b05805429bcc1 Mon Sep 17 00:00:00 2001 From: HaRoLd <303926+HarryR@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:11:46 +0000 Subject: [PATCH 21/21] predict-pcrs: list replay events in firmware log order Events were grouped by PCR. Only the order within one PCR affects its value, but a platform that routes events into another PCR (GCE TDX logs the GPT and BOOT*.EFI into PCR2) needs them in the order they really reach it: GPT, then the application. The order matches OVMF and GCE event logs. Same event set; pcrs.json byte-identical on x86_64 and aarch64. Co-Authored-By: Claude Opus 5.5 --- tools/predict-pcrs.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/tools/predict-pcrs.py b/tools/predict-pcrs.py index 70a8adc..cc114ee 100755 --- a/tools/predict-pcrs.py +++ b/tools/predict-pcrs.py @@ -22,6 +22,9 @@ # logged. An input (the payload is the deployment's choice). # PCR8-13, 15-23 not extended. # +# Events are written in the firmware's log order, not grouped by PCR, so that a platform file +# routing some of them elsewhere (GCE TDX logs the GPT and BOOT*.EFI into PCR2) keeps their order. +# # Not modelled: PCR0-2 (provider firmware code, firmware boot entries, option ROMs). They are the # platform's, inside the trust boundary its vTPM already implies, and change with its firmware # updates: a per-platform replay file (golden readings) supplies them. @@ -138,16 +141,10 @@ def esl(role: str) -> dict[str, Any]: sep_expr = {"hex": SEPARATOR.hex()} # (pcr, type, by, about, derivation, digest mode, bytes for the local computation) G, S = mv.EFI_GLOBAL_VARIABLE, mv.IMAGE_SECURITY_DATABASE + # In the firmware's log order (OVMF and GCE alike), not grouped by PCR: only the order within a + # PCR affects its value, but a platform that routes some of these events into another PCR (GCE + # TDX: GPT and BOOT*.EFI into PCR2) needs them in the order they really reach it. ev: list[tuple[int, str, str, str, dict[str, Any], str, bytes]] = [ - (3, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), - (4, "EV_EFI_ACTION", "firmware", "boot option dispatch", {"utf8": CALLING}, "hash", CALLING.encode()), - (4, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), - (4, "EV_EFI_BOOT_SERVICES_APPLICATION", "firmware", f"stage0 ({efi_name}, Authenticode)", - {"artifact": efi_name}, "authenticode", files[efi_name]), - (5, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), - (5, "EV_EFI_GPT_EVENT", "firmware", "UEFI_GPT_DATA of boot.disk", - {"gpt": {"artifact": "boot.disk"}}, "hash", gpt), - (6, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "SecureBoot = 1", var(G, "SecureBoot", {"hex": "01"}), "hash", uefi_variable_data(G, "SecureBoot", b"\x01")), ] @@ -159,9 +156,18 @@ def esl(role: str) -> dict[str, Any]: (7, "EV_EFI_VARIABLE_DRIVER_CONFIG", "firmware", "dbx (dbx.esl)", var(S, "dbx", {"artifact": "dbx.esl"}), "hash", uefi_variable_data(S, "dbx", files["dbx.esl"])), (7, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_EFI_ACTION", "firmware", "boot option dispatch", {"utf8": CALLING}, "hash", CALLING.encode()), + (3, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (4, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (5, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), + (6, "EV_SEPARATOR", "firmware", "", sep_expr, "hash", SEPARATOR), (7, "EV_EFI_VARIABLE_AUTHORITY", "firmware", "the db entry that verified stage0", var(S, "db", {"concat": [{"guid": str(own["db"])}, {"artifact": "db.cer"}]}), "hash", uefi_variable_data(S, "db", own["db"].bytes_le + files["db.cer"])), + (5, "EV_EFI_GPT_EVENT", "firmware", "UEFI_GPT_DATA of boot.disk", + {"gpt": {"artifact": "boot.disk"}}, "hash", gpt), + (4, "EV_EFI_BOOT_SERVICES_APPLICATION", "firmware", f"stage0 ({efi_name}, Authenticode)", + {"artifact": efi_name}, "authenticode", files[efi_name]), ] events: list[dict[str, Any]] = [] for pcr, typ, by, about, expr, mode, data in ev: