Commit graph

1074 commits

Author SHA1 Message Date
bunnie
a840beb98e
loosen check on key tag
The original check on public key tag was "if the tag doesn't match
one of four approved tags erase secrets".

With third party images, third parties can pick their own tags - so
as-writ this would constrain third parties to have to use the same tags
as baochip, which is too restrictive.

Change the check to explicitly trigger erasure if and only if
the tag is "dev ". Note there are plenty of other checks around as
well so this is not the sole check, thus I think loosening this
permission is good for keeping hygiene between third party firmwwares
and baochips own firmwares.
2026-02-03 18:33:33 +08:00
bunnie
f96c01634f
streamline acram/slot manager access
Reviewing the code, I was decomposing multi-element slots
into individual slots, but erasing them as a multi-element slot.
This results in unnecessary churn.

The barrier to doing a simple check on the full slot all at
once was a missing API for unchecked reads of the full slot:
during checking, we want to be able to retrieve the contents
even if technically the ACL access is denied (note that the
ACL is enforced in *hardware*, the software based check of
the ACL is just a "belt and suspenders" check).

So, this patch adds a routine that allows for an `unsafe`
retrieval of the slot data regardless of the ACL, where the
safety condition is that the caller has to be aware that
junk data could be passed to it if the ACL isn't correct.
2026-02-03 18:12:18 +08:00
bunnie
e349703fd5 automatically adjust BIO clock dividers on sleep
this allows the BIO to continue to function even though
the CPU core is in WFI. It isn't running at full speed, but
for some applications (such as WS2812 LED driving) the lower
speed is perfectly adequate and you save a lot of power
by turning off the CPU core.
2026-02-02 23:37:48 +08:00
bunnie
7f6b045681 optimize timeout handling in spim interface
while debugging the disconnect issue, discovered that the timeout
routine in `std` was extremely wastefully blasting the name server
to connect to the ticktimer every time it was called. yowch!

this patch does the following:

- cache the ticktimer connection in an AtomicU32
- check if the transaction is done on the "Fast path" before
doing any waiting
- check again after fetching time - at this point, most transacitons
are actually likely done
- only then, do the wait loop

this greatly speeds up screen drawing, it seems.
2026-02-02 01:22:26 +08:00
bunnie
be5e817c7c expose register manipulation as public functions
the library is a bit too specific to a given application
without the generic API being exposed. i.e. the way it was
originally generated would imply that every scenario for
the driver would need to be implemented in the library-side
HAL, when in reality, I think it makes much more sense for
the customization of registers (especially when debugging)
to live near the device side.
2026-02-02 01:20:41 +08:00
bunnie
d466abd456 strip out disconnect idiom in the HAL crate 2026-02-02 01:20:14 +08:00
bunnie
8bc480994c remove disconnect idiom from HAL API
the implementation is flawed - because multiple APIs hit
a single server, the reference count can reach zeoro for
a given interface, and trigger a disconnect, while another
API is still using it.

the long-term fix for this, if we wanted auto-disconnect,
would be to wrap the connection query into a helper that
uses an Arc to ensure the count is maintained across all
possible interfaces.

However, for the HAL, it's likely that pretty much every
server is going to want this connection, and want it to
stay around so - we'll just remove the auto-disconnect
idiom for now and figure something out if we end up
hitting a connection resource limit on a service that
truly only needs the HAL connection early on in its
lifecycle and never needs it again.
2026-02-02 01:17:24 +08:00
bunnie
4a7ed1315e add maintenance notes 2026-01-30 04:26:15 +08:00
bunnie
d44caab9ec update api for publishing 2026-01-30 04:22:33 +08:00
bunnie
3f869ca389 bump utralib version for publication 2026-01-29 19:12:00 +08:00
bunnie
88ccc7e042 fully specify the bao1x target on blitstr2 for bao1x builds 2026-01-29 18:58:55 +08:00
bunnie
5267335346 in practice, we never want to kill the HAL service, so remove the option 2026-01-29 00:10:09 +08:00
bunnie
b2cf705c59 bump ticktimer version to drop susres dependency 2026-01-28 20:53:57 +08:00
bunnie
75f75ebffa add hooks for oem-baosec-lite in the clock and power management 2026-01-28 15:04:06 +08:00
bunnie
45632385d5 downgrade susres to a common api
doesn't make sense to push this to crates.io because it's not
common across all platforms, I think.
2026-01-28 00:36:05 +08:00
bunnie
ece9b9943c add module 2026-01-27 22:20:56 +08:00
bunnie
f288a18040 add a first whack at an lis2dh12 accelerometer driver
This is a ball of Claude-generated code which was guided by
the datasheets, some trait APIs and other prompt info.
The prompt used to generate the code is appended to this file.

The result is structurally pretty similar to the accelerometer
driver templates I've seen provided by the vendor, except in Rust
and with Xous idioms, so I think this is a pretty reasonable
whack at reducing boilerplate. There's way more features in these
accelerometers than I have time to write getters/setters for.

The few functions I have used look good insofar as getter/setters,
but there are some oddly specific defaults in the file that should
probably be corrected, probably due to over-prompting of the code
generator. I'll work through these over time.
2026-01-27 22:10:14 +08:00
bunnie
1db717a63f add put_pixel_unchecked() trait in API
this is for implementing checked, higher-performance loops
like blits.
2026-01-27 22:09:37 +08:00
bunnie
b34f4a4c6f remove failure case in Drop implementation
this is some technical debt - Drop doesn't coordinate across
all instances of an object and so the disconnect isn't able
to know exactly when to disconnect. This will require some
guru meditation later on to correct this in a "proper" fashion.
2026-01-27 22:08:28 +08:00
bunnie
385c356801 refactor clock computations & add routine to determine fd
this is a prelude to clock tuning the internal bus networks
for bandwidth. The "trivial" thing of just cranking the speed
up to the edge and letting the dividers didn't seem to help
performance much, though; this could be due to the clock synchronizers
beating against each other.
2026-01-27 22:07:07 +08:00
bunnie
f7c00eb985 fix some rendering artifacts and add todo's on the QR code rendering 2026-01-27 22:04:51 +08:00
bunnie
ac20b43aaa update gc2145 comments 2026-01-27 22:02:24 +08:00
bunnie
1cb23dd4a2 change power-on order of display and add unchecked variant of put pixel
- remove bounds checking for accelerating blits that are already checked
- fix the command ordering for display power-on to remove "noise"
during power-on of the display.
2026-01-27 21:51:50 +08:00
bunnie
d6a5c636bb "best" config with current lens 2026-01-27 17:33:22 +08:00
bunnie
9d5851bd98 adjust attack threshold trip for recording attack
in practice we're seeing multiple trips to the glitch detector
when power down discharge is slow.
2026-01-25 18:32:24 +08:00
bunnie
84e276f712 add BIO sketch for qspi to 8080 converter
quick feasibility study to confirm that BIO can convert
a QSPI video stream into 8080-style display stream support.
One of those quirky weird applications that I think BIO is
kind of perfect for.

I think it should work, at the speeds required, but nothing
compares to actual hardware testing.
2026-01-24 23:55:22 +08:00
bunnie
4523fea62c add support for more board options
- oem-baosec-lite board support
- more flash memory types
- transparent polarity switching on reset line

The reset line in particular is having its polarity switched
because the I/Os pull-up by default, and we'd like the reset
line for peripherals to be asserted on reset (this prevents
glitching on e.g. displays while the CPU boots).
2026-01-24 23:49:19 +08:00
bunnie
42a55cc238 add support for more flash memory types 2026-01-24 23:48:57 +08:00
bunnie
27250c65dc move anti-rollback check to after the signature has been validated
I decided i feel too uncomfortable doing any state changes based
on unvalidated data. I can't see a downside to moving the check
to only after the signature has been verified.
2026-01-22 23:15:53 +08:00
bunnie
04dd447745 add anti-rollback checking to the signature check routine
one minor issue with this implemnetation is it requires dev
images to have an anti-rollback counter that matches or exceed
the last signed image seen.

This is more of a developr ergonomics issue - this will certainly
lead to some surprise by developers who are trying to take
production devices and "downgrade" them to an old dev tree
that has an old anti-rollback firmware number in it.

However, I think this is navigable and probably the simplicity
of not having an "escape" path for dev-signed imgaes is worth it.
All a developer has to do is to set the anti-rollback version
number to be equal to or greater than what was reported in
the device.
2026-01-22 19:48:37 +08:00
bunnie
23b7bc0142 add an upper limit for counter increments
this is a sanity check number that can be used by firmware
to vet a counter value before incrementing to it. it's particularly
useful to thwart wear-out attacks agaisnt anti-rollback firmware
versions, i.e. by specifying an extremely high anti-rollback number
one might be able to cause a reset-to-0 failure and this prevents
that from happening by limiting the maximum value of the the
counter that can be requested.
2026-01-22 19:46:07 +08:00
bunnie
9d972f59d5 add specifications for anti-rollback and receipt tracking
anti-rollback is a number that is stored in a monatomic counter
inside the device that is compared against the firmware images
presented to the device. If the image version is lower than the
anti-rollback counter, the image is rejected. If the image is
higher, the anti-rollback counter is incremented until it equals
the vesrion in the image.

the receipt mechanism is a method for ensuring that cross-third
party signed images can't be used to dump keys on other third party
images. Every time a boot1 is accepted, a copy of the key block
that was used to accept the third party image is stored in the
receipt block.

If those keys rotate, then the collateral keys are rotated. this
prevents a rotation of third-party images from being used to
dump other third party images.

it does mean that third party signers have to be careful to not
rotate any of their signing keys uninitentially.
2026-01-22 19:42:51 +08:00
bunnie
97df81de44 fix permissible function code on altboot
this allows recovery from revoked keys and trying to load
a dev-boot signed image from alt-boot loader
2026-01-19 03:34:55 +08:00
bunnie
18a58c7d18 add more graceful handling of erase inconsistencies 2026-01-19 00:18:13 +08:00
bunnie
763a2c290d make boot more forgiving of inconsistent initial values 2026-01-18 22:37:08 +08:00
bunnie
6b7ff11b4e
add collateral erasure and checking of IFR copy of pubkeys
The IFR copy of pubkeys is truly actually indelible because
of the no-exceptions write inhibit byte. Add code to check
against that copy.

Note that the IFR region's downside is the presence of
the write-inhibit byte means the check is complicated
as the full key is striped across two locations, but
this code handles that.
2026-01-18 02:56:14 +08:00
bunnie
491a1c14dc add key range for collateral 2026-01-18 02:17:25 +08:00
bunnie
2b19c4bd21 add a command for setting the bootwait flag
The keystore is a sensitive server, and the one-way counters
have security-critical propoerties. So instead of revealing a
generic one-way counter API to the world, specific, limited
requests to do things are going to be created for the keystore.

In this case, the bootwait flag would be convenient to be able
to set from userspace. The motivation for this requirement is
actually continuous integration - a normal human could just
hold down a button while turning on power, but in CI, I don't
have a robotic thumb (or an alternative electrical signal) to
simulate the nerve-pinch on boot.

Previously I was "cheating" and simulating this by nuking the
loader, which effectively forces a bootwait.

However, in production, this is *not possible* because the JTAG
port is sealed off. Thus, this may be the first of a series
of small PRs to incorporate CI tooling that clears up tech
debt like nuking the loader to get into boot wait.
2026-01-16 17:32:12 +08:00
bunnie
bf721e3b5c
adjust permissions on serial number; make chip init more permissive
It is not clear if I can get the factory to burn the serial number
(wafer lot, ID, x/y location) into the location I want it to be.
So, I am allowing this to be updated by the firmware on boot,
thus necessitating the permissions to be writeable for the serial
number field.

Furthermore, if there is any error in initializing the chip's
identity in the factory, right now the chip goes into a mode
where it has crashed and can't run diagnostic code. Write errors
in this stage are thus turned into .ok() instead of .unwrap()
because we want to allow the chip to go through the whole flow
and then diagnose any issues later on.
2026-01-15 16:58:22 +08:00
bunnie
a5a6cc8e48
Fix comments in production key 2 slot 2026-01-15 16:57:27 +08:00
bunnie
3e5b62aab3
Add production public key to the first key slot 2026-01-15 16:56:43 +08:00
bunnie
29d25c13a1 refactor UDMA UART to use "poll" mode to receive data
The prior implementation tried to use the UDMA streaming mode
to get Rx data out of the UART.

The problem is that with streaming mode, it's hard to tell how much
data is actually available. This is because the thing that sets up
the stream sets "some number of bytes" as the fetch depth of the
DMA Rx, but all you can read is "number of bytes remaining" out
of the DMA interface.

So when 0 bytes are remaining, you can fetch some data, but you don't
know *how much* to fetch. And if someone else fetched partial data
before you, you don't know how much partial data was fetched. This
could be resolved with some gnarly, highly concurrent state that
gets incremented on every fetch.

Or, we could use poll mode. There's a reason i think it's in the
block, because the Rx DMA mode is more or less not usable. Poll
mode you read a config register, see if there's valid data, and if
so, when you read the data register, it's pulled out of a FIFO.
The FIFO is in hardware and it's 4-deep. As long as you don't
need more than a depth of 4, you're rock solid.

This is a lot easier than the UDMA Rx mode, so I've just gone ahead
and deprecated the Rx mode. I could only ever get the Rx mode
to work to receive a single character *anyways*, so despite its
potential to receive thousands of bytes without CPU intervention,
it was only ever used as a 1-deep buffer because of the inability
to know exactly how much was in the buffer. Thus, the poll mode
is actually an improvement over the DMA mode, in practice.

More importantly, it means the Rx link is much more stable in
GDB kernel mode, if the baud rate is cranked down to 115200 (at
1M baud, the kernel still can't respond quite fast enough to
reliably drain it).
2026-01-14 03:21:06 +08:00
bunnie
24105e7b22 add the default perclk speed as a public constant
instead of just hard-coding it in the clock setting routine
2026-01-14 03:20:27 +08:00
bunnie
fba011db3a commit version bump so that we may publish our packages 2026-01-08 03:04:19 +08:00
bunnie
079ec33134 improve formatting & timing slightly 2026-01-06 15:43:50 +08:00
bunnie
d1a3eb4b58 handle clock counter rollover case & fix bug in assembly register naming
t3 doesn't actually exist
2026-01-06 15:40:14 +08:00
bunnie
08cfe2d724 cleanup warning 2026-01-06 13:41:24 +08:00
bunnie
1087405eb9 add compatibility for APS6064L SRAM parts 2026-01-06 12:14:20 +08:00
bunnie
b49856ce7b change the pin set API to something more usable 2026-01-05 21:55:14 +08:00
bunnie
dd18ddf97c convert avalanche TRNG interface into the Xous BIO API 2026-01-05 21:53:39 +08:00
bunnie
b02f1563ae don't put pin snapping into ws2812 implementation
the pin snapping makes the application not composable with
other applications that don't use the exact same snapping mode.
2026-01-05 08:56:38 +08:00
bunnie
40e740d869 implementation for the composeable I/O modes 2026-01-05 08:56:20 +08:00
bunnie
d647e41822 fix API to allow for composition of IO configurations
the main issue is that if the IO configuration fully replaces
a previous configuration, two apps can't be loaded at the same
time because the later one replaces the previous one's configuration.
now the I/O settings take an option for a configuration mode,
which is somewhat clumsily expressed as either replacing the
I/O configuration, setting bits only, or clearing bits only.

This maybe could use a cleaner API but not quite sure how to
do it yet.
2026-01-05 08:54:29 +08:00
bunnie
9a94ea48ad add captouch demo
some basic APIs in place to help make touch a little easier
to use.
2026-01-05 08:53:13 +08:00
bunnie
6398415265 update lib refs 2026-01-03 22:55:47 +08:00
bunnie
e2097f171e add demo for doing multiply instructions 2026-01-03 22:55:20 +08:00
bunnie
e0fddfbe04 improve readme slightly 2026-01-03 22:55:04 +08:00
bunnie
c81911e498 move readme to a customary location 2026-01-02 12:54:01 +08:00
bunnie
f1b9212b75 re-organize code so that the APIs are up top 2026-01-02 12:45:40 +08:00
bunnie
f9e17f7a63 add a README for the BIO libraries 2026-01-02 12:42:46 +08:00
bunnie
785daf253c update comments 2026-01-02 12:30:10 +08:00
bunnie
acaa3b6874 cleanup warnings 2026-01-02 12:26:09 +08:00
bunnie
437c5e1d85 start the bio-lib
this is where a collection of BIO applications will eventually live...
2026-01-02 11:25:49 +08:00
bunnie
35cdc0c0f5 resource tracking implementation 2026-01-02 11:25:37 +08:00
bunnie
8d84345444 add resource tracking 2026-01-02 11:25:18 +08:00
bunnie
24b6d4cb42 fix bugs in implementation 2025-12-31 23:34:35 +08:00
bunnie
06501a9032 fix handle API to reflect actual implementation
I had a bit of a brain fart while drafting the original code
2025-12-31 23:32:39 +08:00
bunnie
5be682b37f cleanup apis after std implementation 2025-12-26 21:03:19 +08:00
bunnie
acc9771886 first cut at the low level implementation 2025-12-26 20:18:06 +08:00
bunnie
c239d79ead cleanup the API after running through an implementation 2025-12-26 20:17:34 +08:00
bunnie
8c3c23ea85 add the core hardware API implemenation for bio
should work for both no-std and std environments, but lots and
lots of testing TBD...
2025-12-26 20:16:47 +08:00
bunnie
9eb40aceb0 move comments to the correct file 2025-12-26 01:06:10 +08:00
bunnie
68679f41ba add the 'std' implementation side of the abstract BIO API
this is essentially the getter/setter that translates
BIO api calls into messages that would be sent to the BIO
server implementation. The BIO server implementation would
have the actual BIO hardware calls in it. These calls, if
written correctly, also double as the no-std implemnetation
of the BIO API.
2025-12-26 00:58:49 +08:00
bunnie
60b18303ed define the BIO API in the abstract API
this is a fully abstracted API that should be fully hardware
independent. This is meant to supercede the xous-bio-bdma library.
The xous-bio-bdma library will stick around, but its main purpose
is as an experimental, baremetal library that contains low
level code and test code for developing the hardware. We could
try to merge this into the abstract APIs but I think it doesn't
make sense from a methodology standpoint - hardware development has
a different tempo and flow from the software development process,
and so by keeping these two separate we end up with potentially
diverging APIs - but actually, this is a good thing. It allows
us to develop e.g. v2 of the hardware without having to roll
uncertain/experimental v2 hardware APIs into the abstract APIs
right away.

there is one hairy point in all of this, which is I'm trying to
get fancy and have a hardware "handle" be dropped automatically
when it goes out of scope. This requires me to pass around
a phantom lifetime parameter, something I haven't done before.
If this works, it could be a good template for dealing with other
abstract hardware APIs that will help remove some unsafe code.
2025-12-26 00:55:00 +08:00
bunnie
444d7b310e re-enable keyboard bouncer inside bao-video hosted mode 2025-12-24 13:14:48 +08:00
bunnie
88a6492481 make the signature check/security elements more clearly optional
the problem with it being default in most configurations is that
it pulls in a sha-2 and ed25519 dependency into routines that
never rely on them. now libs that rely on the sigcheck need to
specify the feature explicitly to pull in the depedency.
2025-12-22 16:17:08 +08:00
bunnie
30725c5169 add deep sleep mode 2025-12-22 02:10:09 +08:00
bunnie
a5303a707f define backup flags 2025-12-22 02:05:46 +08:00
bunnie
39eb15003d work around buram erratum; convert reserved field to flags
- backup RAM has an erratum where two locations are corruptable
and should not be used between soft resets to store data

- the reserved 32 bits in the bureg are now accessible as flags.
these flag bits are used between boots to coordinate system state
information.
2025-12-22 02:04:31 +08:00
bunnie
b195447fcb add swap key to the list of keys managed on baosec
not sure why this wasn't added earlier....
2025-12-19 16:42:04 +08:00
bunnie
68841a45b4 add self destruct support
this will wipe a chip to a factory-blank state. It's unrecoverable
on dabao: fully bricks the board.
2025-12-19 16:41:16 +08:00
bunnie
0c18c62d0a move the key consistency check to a library
this allows us to refer to it in boot1 if we eventually decide
it's useful to do it there.

however, as a matter of policy, boot1 checks loader signatures
against *boot1*'s public key block - so if the loader is to be
signed with a different key, boot1 needs to be updated.
2025-12-19 16:06:50 +08:00
bunnie
5195d46d7b add println_d! macro to bao1x-hal
this allows forcing prints to go to the duart

this is useful for debugging early boot issues
2025-12-19 03:30:20 +08:00
bunnie
e5790d76a3
lighten up the mesh debug
actually there's no reason i think to have it print all
four checks - just have it print on two of them, just in
case for some reason the prints could be used to time a glitch.
2025-12-19 03:29:30 +08:00
bunnie
2c80de4933
modulate countermeasure sensitivity & reporting
The "attack" counter notches up when a board goes through a
"slow" powerdown, as would be the case on a system that has
a lot of capacitance relative to the chip. This is a false
signal.

It's hard to tell this apart from a glitch attack, so a
heuristic was applied where at least two glitches have to
be seen before declaring we're under attack.

Note that in paranoid mode, the board instantly resets
when the power gets too low, so the counter doesn't notch
up.

A print statement indicating when a mesh violation was
added - this is to help debug chips that have a weak/marginal
mesh. Because the mesh is so long, small manufacturing defects
in the mesh are also picked up by the mesh sensor...
2025-12-19 03:24:11 +08:00
bunnie
0c690d8be4
add boot1 pubkey integrity checking
this should erase the secret keys if the boot1 pubkeys don't match

this enables OEM-signed boot1 images. the policy is that all OEM
images signed by baochip are considered to be untrusted, and thus
loading them onto a device would wipe any secret keys, making
them less useful for extracting secrets.

There are 2048 keys and about 500 keys are used by baochip,
so there are still plenty of keyslots available for OEMs to
use to implement their own version of security.
2025-12-19 01:14:51 +08:00
bunnie
49e526f60b
simplify erased key reporting on debug
this reduces the amount of prints for a key range being
erased so if the debug flags are on boot isn't delayed
while the debug prints. instead, a total tally of the
erased keys for a key range is printed.
2025-12-19 01:12:57 +08:00
bunnie
36b103ef6c
remove the developer function from the function code list
The developer function was decided to be overly-broad: the
issue is you could slot that in to *any* boot position and
it'd be accepted, and we already have a mechanism to deal
with developer mode (developer-signed images). Thus eliminate
the extra case and simplify the code base to reduce
potential bugs.
2025-12-19 01:09:44 +08:00
bunnie
d6c662b378 memoize some common clock settings
this reduces boot time because the space to search for
an arbitrary clock setting is pretty big.
2025-12-18 02:22:38 +08:00
bunnie
9093bb4ed7 simplify keystore setup
The TL;DR is this now treats dabao exactly the same as
baosec in terms of keystore setup from the security flow perspective.

baosec & dabao were different originally because baosec would
rely upon the Avalanche generator TRNG as supplemental randomness
and dabao would not. This special case had to be handled in the
bootloader and propagated through.

However, in a previous commit, the keystore setup was moved to
the OS *anyways* - thus making this difference moot.

This patch backs out the one-way counters that would track the
dabao initialization state.

It also doesn't fail the boot on the erase key proof check
failing if the keystores aren't initialized yet. This creates
yet another condition that could be glitched over to bypass
the erase check but it is checked twice indepedently.
2025-12-18 02:16:50 +08:00
bunnie
d874c3e5c2 commit for version bump 2025-12-16 02:02:37 +08:00
bunnie
b31c7d411d major rework to clock settings
this is a big, ugly, multi-file commit but it turns out when
you start shaking one part of the clock tree everything rattles
along with it.

Basically this updates the clock tree to use a search for an
optimal setting instead of a hueristic/table lookup, and then
a bunch of small bugs in the clock settings were found that had
to be proopagated to dependent crates.

i2c clock set now seems ... more correct, the frequency is
not overclocking the bus (was at 600khz before, now just below 400khz)

the uart equations finally sees sane

the spi clocks check out

the only inconsistency left is that i can't seem to get a fractional
division on peri clk. it would be really nice to be able to do a
fractional divide and get a little more peformance out of the spi
busses but i think it just doesn't work that way - the "fractional"
division is actually more of a "time-average frequency is correct"
but when you go into fractional mode it's spending some time pulsing
at 2x the rate and some time at 1x the rate to get to the time average
frequency, and when you're at the 2x rate things break.
2025-12-16 01:02:00 +08:00
bunnie
679ece9b19 major rework of the clock-set routines
the routines provided in the reference crossbar libraries are
not great and the recco of their team is to just use hard-coded
table lookups. Replaced this with a computational method that can
find arbitrary clocks; however, the computation *is* somewhat expensive
because you have to iterate through a fairly large solution space
to find an "optimal" solution.

That being said, these solutions can be memoized if they are
frequently re-used. I rather prefer this method than just an undocumented
table lookup.

More testing is needed but the initial results look pretty good.

Also peripheral clock setting is reworked to be more clear as to what
is going on. I think I finally have some clarity on why a mysterious
"divide by 2" was ending up in everything; other dependencies have
been reworked to clean that up. I think actually I may have been
overclocking the peripheral bus by a factor of 2 prior to now :-/
2025-12-16 00:58:37 +08:00
bunnie
021cf609e4 remove wfi apis from hal
this is now in the susres crate
2025-12-16 00:58:10 +08:00
bunnie
8dc1e9c837 rework backup RAM hashing to ignore the erase proof slice
a slice of key material is written to backup RAM from boot0
all the way to the loader, to prove to the loader that secret
keys were erased in a higher privilege state (loader then erases
the key, and this key is considered leakable without harm to
security).

The problem is that writing the key to backup RAM in boot0
was fixing the hash on the backup block, which is before
the check happens to see if it was a cold power-on. This would
defeat the RTC setting & backup setup logic.

THe solution to this is to exclude that one key from the hashing
area and special case it. A set of routines and API names were
added to help enforce this case.
2025-12-15 15:19:01 +08:00
bunnie
3fd9087b7f commit a partially working wfi cycle 2025-12-11 02:28:37 +08:00
bunnie
df3529d595 add power down/up opcodes to the gfx layer 2025-12-11 02:21:40 +08:00
bunnie
261ea7a880 update apis in hal-service 2025-12-11 02:18:44 +08:00
bunnie
8950a24327 move i2c in bao1x-hal-services into bao1x-hal
this makes i2c accessible without having to rely explicitly
on the server itself, making the library callable in more contexts.
necessitated avoiding a name space collision and moving the
I2C hardware drivers to a stucture named I2cDriver; the I2C
object now unambiguously refers to the userspace interface
to I2C.
2025-12-11 02:13:21 +08:00
bunnie
8269f9f759 update apis to accommodate power savings mode 2025-12-11 02:10:25 +08:00
bunnie
0a47620da2 add powerdown api to sh1107 2025-12-11 02:09:15 +08:00
bunnie
a3a566b240 add API calls for debugging kernel under baochip targets
also updated some really bit-rotted docs

we will deprecate the docs/ directory soon, they are wrong
and misleading at this point.
2025-12-09 16:19:04 +08:00
bunnie
41d09786ae tighten up clock gates in boot0
confirmed that these settings do not affect the glitch sensors.
2025-12-08 16:54:23 +08:00
bunnie
a3f9a9942d update APIs to use the central clocking implementation 2025-12-08 15:58:27 +08:00
bunnie
11b506bdc4 build a consolidated clock setting routine
This routine pares down the clock setting routine to hopefully
a core minimum set of side-effects while allowing the system
to boot.

It also takes the register bank offsets as arguments, as well
as various functions to accomplish different tasks as argument,
so that it can be used in different contexts (such as in `std`).

Finally, the BIO clock rate can be set to slow or fast. The power
cost of the fast setting is about 12mW. If you're not needing
the high speed features of the BIO, slow setting is probably what
you want.

Currently, the system is configured such that after boot1, the
BIO is running in slow mode (to save power for battery powered
configurations); and then the clock set calls in baremetal and
dabao bump this up to the fast speed since these two configurations
are assumed to be running off of a USB wire with ample power.
2025-12-08 15:55:20 +08:00
bunnie
4e0b67878a remove old code 2025-12-07 19:00:29 +08:00
bunnie
ebb7e8dfae refactor QR code notification implementation
Previous implementation sent the QR code as draw commands.
This is inefficient as it would require hundreds of draw
commands to be sent per QR code rendered.

This implementation codes the QR code as a bool and sends
it in a single memory message, and implements a QR code renderer
on the receiver side.

The QR code rendering is also cleaned up so that the QR code is
always centered and takes the full screen, to give the best
conditions for someone scanning the code from another device.
2025-12-07 18:58:33 +08:00
bunnie
53c7a729f7
add primitives for interrupt-based glitch handlers
glitches can trigger interrupts from several sources:

- ECC errors on multiple blocks
- consistency check errors on hardened logic
- light sensor
- voltage sensor
- glue cells

These primitives respond to these glitches in an interrupt
context. At the moment, by default a fairly lax approach is
taken to responding to the glitches: partially, we want to make
sure that the sensors aren't too sensitive and trigger by accident.
The final thresholds can be adjusted fairly readily.

In addition, the mesh can trigger an interrupt, and typically,
that interrupt is a false reading (because the mesh takes a
long time to settle, and we boot the system while the mesh
settles). Thus, we take an approach of polling the mesh
effectively, and when interrupts happen due to the mesh we
just clear it and ignore it and allow the polling routine
to manage the mesh. The mesh is theorized to be a static
attack, anyways.
2025-12-07 01:33:53 +08:00
bunnie
15ac4d8529
add primitives to buram for storing slices
this is used by the key erase proof routine, but will be
useful in general for storing data in the buram

also, the ranges of slices are currently defined at
the top of the file but might be moved somewhere more
maintainable later.

RRAM writing got bollards added to it, as RRAM write could
be a glitch target: if a glitch could manipulate the
address somehow to stick stuff at an arbitrary location,
during write, that would be bad. However, it's probably
also reasonably dangerous to try and glitch RRAM writes
because there's a chance you spray over off-target items
and thus trigger a signature check failure on your next
boot.
2025-12-06 18:36:51 +08:00
bunnie
09e68291cf
during key erasure, add the proof that secret keys were erased 2025-12-06 18:35:43 +08:00
bunnie
eee9cd62c9
enable secure erase confirmation in loader (leaks one chaff key)
A problem was discovered while implementing the secure boot
hardening. Namely, an attacker could trick the loader into
loading a devkey-signed kernel by incrementing the
developer mode counter without actually triggering the
secure erase of the keys, and finding a way to glitch
over the check of the developer mode counter check.

Two countermeasuers are implemented:

1. if the developer mode flag is set, trigger a secure erase
even if the image signatures aren't developer mode

2. leak one of the chaff keys into the loader, so there are
now at least two indpendent checks of being in developer
mode in the loader. One is based on the counter, which
is only weakly correlated with the erased state. The
other is checking for the erase value in the leaked key,
which is a strong indicator of being in developer mode.

The leaked key is, of course, erased before entering the
kernel (and the key is leaked into a region of memory
that is, in theory, securely claimed by the keystore, so
it's not like anyone can just read it; however, it is
in a less secure location than the protected key area).

The impact of an adversary obtaining the key is only
a slight weakening of security because the chaff keys
are numerous, they still have thousands of bits to
guess even if they got a couple hundred of them.

The next series of patches implements the scheme outlined
above, starting with defining the key to be leaked. The
leaked key is intentionally the last key in the slice
of keys used in the erasure algorithm, so that presumably
if the leaked key is showing an erased value, all other
keys have been erased.
2025-12-06 18:24:40 +08:00
bunnie
9ddf6beae6
move the kernel start address
this correctly gives the loader 256k of space, which is what
its link file specifies. The loader was previously under 128k
by chance, but with glitch hardening it's grown past that
boundary.
2025-12-06 18:23:10 +08:00
bunnie
b99b4cb665
cleanup signature checking API
Signature checking parameters are now consolidated into
a single "SecurityConfiguration" record. This allows the
sum total of security state transitions to be summarized in
the bao1x-api/src/pubkeys/mod.rs file, easing maintenance
and audit.

Reaction to the signature check is split into a `hardened_erase_policy`
API call which can take the results of the signature check and
react to it if necessary.

This allows the signature check routine to be used for both
audit (where reaction is not necessary) and for live testing
of the code (where reaction is required). It also simplifies
the implementation of double-checking signatures in the case
of paranoid mode.

Another important improvement is that the signature checking
API outputs the target address for the jump, but masked with
an XOR of the function code of the signed block. The purpose
of the XOR mask isn't to obfuscate the value; rather, it's
to prevent there being a single, simple, fixed-constant
jump instruction laying around that a glitcher can use as
a target: instead, a pair of registers must be loaded
with the target and its mask. This is an example of what
the final jump looks like:

```
60003a8e:	ffffffff          	.word	0xffffffff
60003a92:	0440006f          	j	60003ad6 <bao1x_hal::hardening::die>
60003a96:	ffffffff          	.word	0xffffffff
60003a9a:	167d                	addi	a2,a2,-1
60003a9c:	fe71                	bnez	a2,60003a78 <rust_entry+0x2f74>
60003a9e:	a00d                	j	60003ac0 <rust_entry+0x2fbc>
60003aa0:	0360006f          	j	60003ad6 <bao1x_hal::hardening::die>
60003aa4:	ffffffff          	.word	0xffffffff
60003aa8:	02e0006f          	j	60003ad6 <bao1x_hal::hardening::die>
60003aac:	ffffffff          	.word	0xffffffff
60003ab0:	0260006f          	j	60003ad6 <bao1x_hal::hardening::die>
60003ab4:	ffffffff          	.word	0xffffffff
60003ab8:	01e0006f          	j	60003ad6 <bao1x_hal::hardening::die>
60003abc:	ffffffff          	.word	0xffffffff
60003ac0:	0149c533          	xor	a0,s3,s4
60003ac4:	600805b7          	lui	a1,0x60080
60003ac8:	d0058593          	addi	a1,a1,-768 # 6007fd00 <_etext+0x6e9dc>
60003acc:	82aa                	mv	t0,a0
60003ace:	852e                	mv	a0,a1
60003ad0:	4581                	li	a1,0
60003ad2:	8282                	jr	t0
```

So here you can see the alternating bollards in the region that
will cause any glitches that don't land exactly right to
either halt the machine or cause a reaction.

Line 0x6003ac0 is where the xor happens to compute the target
address. Should a glitcher land on that address, `s3` and `s4`
will need to be loaded with the target address and a value when
XOR'd with it that yields a meaningful result. While there is
a non-zero chance that this can be arranged, it's definitely
not as easy as targeting a jump-to-fixed address exit sequence.
2025-12-05 22:57:34 +08:00
bunnie
d9d146352f
ensure that hardened_get2 is used correctly with an assert 2025-12-05 22:43:49 +08:00
bunnie
32ffba0931
introduce security configurations
The management of different security configurations was getting
a bit out of hand, so all the security configurations used by
the system and their transitions are now consolidated into a single
file, This will make auditing and checking the transitions a lot
easier.
2025-12-05 21:37:21 +08:00
bunnie
1dbb65cc97
zerorize backup registers & fix aoram range in zeroize
backup registers are a high priority target on zeroizing
because it would contain the ephemeral unlock secret, e.g.
PIN code.
2025-12-05 00:59:59 +08:00
bunnie
9e5c57b7de
inline the pll check
this prevents it from being a single area that has to be patched
to bypass the pll check
2025-12-04 15:30:43 +08:00
bunnie
362124127e
add redundant counters, paranoid mode, attack counters
This allocates some additional one way counters dedicated
to hardening:

- Paranoid mode is duplicated in slots 65 & 67
- An attack counter is in slot 66
- Redundant revocation counters are seated in slot 68

The primary revocation counters are in slot 116. This means
that cutting out the revocation counters would probably require
at least two edits to the memory array - simply cutting the
word addressing line for those columns might be enough to
defeat a counter.

Paranoid mode duplicate is stored somewhat close to the
primary counter, which means it could be subject to a single
line cut to fully defeat the counter, but the space is getting
pretty crowded so I'll leave it like that; I really want to
leave the bottom 64 slots available for application use.

A "flag" key is allocated, plus a dummy flag is committed
to the repo. This is a value that, if retrieved, would
ostensibly bring the retriever glory and bounty, to the
extent that any glory or bounty is to be had (ps: I'm poor
and this project is obscure). The actual flag, of course,
is not in the repo...I hope!

The flag value is different from all other values in that
this is the only shared, common secret across all devices.

All other device secrets are generated on a per-device
basis from the TRNGs. So the flag needs some special treatment
such that it's not overwritten during device keying.

The flag exists because I'm hoping that anyone who manages
to extract it will also provide a helpful explanation of
the procedure to get it out, so that the system could be
patched (if the error is patchable) or rev'd in future
silicon. That being said, a flag retrieval is not necessarily
equal to a full break of security across all devices because
as mentioned above, most device secrets are on a per-device
basis. The flag represents then, the amount of effort necessary
to apply to every device to retrieve the secrets within.
2025-12-04 14:56:07 +08:00
bunnie
31385a5599
start moving clock routines into an API library
clock setting calls, for legacy reasons, are duplicated in all the
stages of the bootloaders. This is a start toward moving these routines
into a common set of calls that improves maintainability.
2025-12-04 14:54:26 +08:00
bunnie
bd08328530
add bollard macro and HardenedBool
These macros are added to the platform-agnostic API crate.

bollard is a macro that can respond to the following argument
formats:

bollard!(): inserts 4 illegal instructions and a jump over them
bollard!(#): inserts # of illegal instructions and a jump over them
bollard!(f, #): inserts # of an interleave of illegal instructions
and a jump to f

the last form is intended to "up the ante" by including a call
to a routine that can shut down the chip and/or wipe secrets
should the defender choose to do that. The other ones just
trampoline into an illegal instruction vector which is a fairly
weak defense because the CPU could once again get glitched out
of that.

HardenedBool is a boolean represented by a high-hamming distance
numeric value so that single-bit flips just lead to an invalid
bool, instead of a change in the meaning of the bool.
2025-12-04 14:50:33 +08:00
bunnie
75fb1a1889
Harden the signature check routine
- key revocation check is fully duplicated and tested twice
- bollards & random delays added throughout the code. Random
delays require passing in a csprng object from the calling
environment.
- the primary go/no-go decision on whether a signature passes
or not is unfortunately not hardenable because the API is in
a third party crate. However, the regions around that call are
random-delayed and surrounded with bollards
- the state bits that determine whether the system is secure
and/or in developer mode are implemented using HardenedBool
- erase_secrets has some delays added to it as well as bollards.
However, it does remain a weakness that an attacker
could pull RRAM power during the erase cycle by just isolating
the RRAM power supply and putting a fast current limit on it,
thus preventing effective erasure by starving the circuit
of power.

Nothing we can really do about an active attack on the power
supply to prevent erasure, I think. It is unfortunately required
by design to have an isolated power supply for the RRAM to perform
elevated-voltage forming at CP time, and so, it should always
be possible to limit the current going into it thus preventing,
at least somewhat, any programming operations on the array.
2025-12-04 14:36:28 +08:00
bunnie
05af4f3f62
add hardened_get() and hardened_get2() to one way counters
One way counters are used ot record some security-critical properties,
such as key revocations and paranoid mode.

Two methods of retrieving the counters so that they are hardened
are provide here. Both of them rely on the fact that any value
other than 0 for the counter means it is set.

`hardened_get()` retrieves the counter value and sums it several
times. It does this *twice*, and returns *both* values as a tuple.
By returning both values as a tuple, it reduces the likelihood
that the compiler optimizes out the redundant read. The receiver
should implement serial checks that operate on the hardened_get()
result (i.e., test one value of the tuple, then test the other
value of the tuple redundantly, instead of OR'ing them together
into a single test)

`hardened_get2()` is for counters that are fully duplicated in
the array. For extremely critical counters, they are stored in
two physically separate elements. This is done to make bypass
of the counter harder than just FIB'ing out a single bit in
the memory array. In the case of `hardened_get2()`, a tuple
is returned, but instead of reading the same value twice, the
tuple corresponds to the summed value over each of the redundant
counters.
2025-12-04 14:29:30 +08:00
bunnie
9294c06d45
Add glitch hardening library
This library contains the following primitives:

check_pll() - checks that the PLL is the primary clock source.
This is important because allowing direct clocking of the system
from the external clock pin makes glitching much, much easier.

die() - a routine that implements a reaction to attacks. At the
moment, we just note attacks and then halt the machine. Eventually,
this could be upgraded to be more reactive, e.g. erasing secrets
or bricking the chip.

Csprng - this is a chacha8 cipher seeded with ring oscillator
TRNG data, plus whatever tiny bit of entropy we can scavenge
from uninitialized RAM (to make it so that it's not as trivial
as cutting the RO wire and tying it to 0 to bypass the library).
There's also a tiny health check on the RO before using it, again,
to make it harder than just cutting the RO wire. The sole purpose
of the Csprng is to generate random delays that frustrate glitching
attacks. The delay is currently tuned to a range of 0-255 iterations
of a loop.

paranoid_mode() - turns on fully automatic reactive sensor
countermeasures. Whenever a voltage glitch is detected, the system
will just reboot.

mesh countermeasures - these set up the secure mesh and the
reaction policy to tamper detection on the secure meshes

apply_attack_policy() - an API call that applies the currently
determined countermeasure in case that the detected attacks
counter has gone above a threshold. The reason we don't simply
react right away is that some countermeasures are fairly
sensitive, and *also*, very importantly, the chip *is* packaged
in a CSP and thus especially for dabao users you will expect
to see random trips of the attack sensors due to environmental
noise (photoflashes, nearby lightning strikes, etc.).
2025-12-04 13:34:01 +08:00
bunnie
852a12645b round out stateful list creation in the ux-api libraries 2025-11-30 21:33:04 +08:00
bunnie
106f7153a1 filter key presses through the video layer
the video layer is the "traffic cop" managing when modals
get focus. This patch creates a feed from the video layer
that listers to subscribe to that filters out key presses
destined for modals.
2025-11-28 18:40:56 +08:00
bunnie
738797754b make widgets respond to the "fire" button 2025-11-28 18:40:33 +08:00
bunnie
720680a931 build a hosted mode dummy for aqcuire qr 2025-11-27 22:10:57 +08:00
bunnie
74134bfac2 add ux-api acquisition features 2025-11-27 16:52:44 +08:00
bunnie
bc4e459e28 convert spim txrx timeout from a hard-error into an error message
occassionally when the bus is loaded, some SPIM transactions won't
complete. this needs to be looked into a little more, i think...
2025-11-27 12:34:40 +08:00
bunnie
7e368d231f add mod refs for kpc_aoint 2025-11-26 20:47:28 +08:00
bunnie
59e8707b1a add hardware abstractions/translation maps for baosec keyboard 2025-11-26 20:47:10 +08:00
bunnie
b021a1bcd3 fix typo 2025-11-26 20:46:54 +08:00
bunnie
40c94b5abc add kpc_aoint abstraction layers 2025-11-26 20:45:12 +08:00
bunnie
1ca144f47f remove stale constants; add an irq handler storage class
constants made obsolete in the latest utra update are removed,
and a storage class for multi-purpose interrupt handlers is added.
2025-11-25 19:08:53 +08:00
bunnie
1ebf9b8d94 use the newly extracted utra; fix ranges
in xous, you can't make a range smaller than 4096 bytes,
so range lengths have to be enforced at an abstraction layer
above the page allocator
2025-11-25 19:08:07 +08:00
bunnie
765a36bd3a add option to defer draw updates
this is helpful for composited UIs
2025-11-25 19:07:32 +08:00
bunnie
d30d889774 add rtc hardware drivers and service 2025-11-24 18:28:00 +08:00
bunnie
960ba350cb add bu_mem locations
these failed to extract automatically from the RTL
2025-11-23 08:48:24 +08:00
bunnie
95c8046111 add backup region abstractions
these persist through a sleep cycle
2025-11-23 08:47:43 +08:00
bunnie
145c2e37b2 raise visibility of the erase value 2025-11-18 23:19:28 +08:00
bunnie
4477af6058 fix broken font rendering in rust 1.91
Rust 1.91 (or perhaps, more accurately llvm?) changed how link
ordering works.

Previously, modules would be linked in the order they were referenced
(e.g. pub mod b; pub mod a; would result in b being at a lower address
than a in the resulting binary).

However, apparently, this has changed and now someone in their
infinite wisdom decided that modules should be alphabetized before
linking.

I'm really not sure why the arbitrary ordering of the human alphabet
is superior to any other system, and also, if you really wanted
things alphabetized, you could just alphabetize them in your
reference order.

Previously the fonts were laid out in a way that tried to minimize
cache thrashing by co-locating certain sets of fonts together.

Now they are just sprayed around through the arbitrary and not
terribly useful permutation funtion of the english alphabet.

Rant off.

This changes the specification of the fonts in the code generator
to be in alphabetical order, making the screen once again legible.
2025-11-18 00:18:55 +08:00
bunnie
ff5cfa7b12 remove panic/resets on errors during secret erase
at the moment this runs a risk of boot-loops depending on the
configuration of the device.
2025-11-14 19:14:35 +08:00
bunnie
ed1f19984f
loosen restriction on zero keys seen during wiping
this is to handle an edge case where an improperly set ACL
on the alpha0 boards would cause a set of keys to be inaccessible
to the boot routine
2025-11-14 16:16:46 +08:00
bunnie
c79a891553 add api to determine current speed 2025-11-14 16:16:30 +08:00
bunnie
1e085a6548 don't make unknown flash a hard panic
this allows an accidental baosec recognition on a dabao board
to not brick the board
2025-11-13 22:19:13 +08:00
bunnie
faecc1cf27 pin RRAM data onto heap
this prevents optimization that move it around and can cause
troubles for `std` mode operations
2025-11-13 18:29:06 +08:00
bunnie
a7477ec53b
Remove key slot implementation; migrate keys to data slots
The -A1 stepping is going to tie the IFR access control
bits for data and key slots together. This is due to an RTL
bug where the key slot maps were typo'd and they ended
up mapping to the same IFR ACL.

We "could" continue to use key slots with a rule that
key and data slots would have to coordinate with each
other and not use the same slot number.

However, because of this linkage, and because there are
other bugs suspected in the keyslot implementation, an
executive decision was made to disregard the key slot
feature in the chip.

The main downsides of this are:

- fewer slots (2048 vs 4096)
- no key access linkage to HMAC auth on SCE

I *think* that's it.

Fewer slots - 2048 slots is still a lot of slots, about half are
used now, I think this is plenty.

Key access linkage to HMAC auth on SCE - I have reasons to
suspect this feature is broken anyways for subtle reasons
related to malleability of the HMAC round constants. Even
without that brokenness, it's hard to use HMAC auth to manage
the system because it requires per-device unique keys: so,
we're using a PKI scheme and no symmetric secrets to handle
access controls.

Removing the key slots also greatly simplifies the code
base analytically. This culling removes the key slot
abstraction the "simple" way, but without the weirdness
of the keyslots (in particular the key ID chaining which
makes them different from data slots) I could remove even
more abstractions and simplify the code.

One upside is now all elements can enjoy the write mode
behavior which can force the slot to be only 0->1 writeable,
which could be useful for other things down the road.

This was tested to not interfere with Dabao-Alpha 0
bootloaders.
2025-11-13 18:21:52 +08:00
bunnie
f88c801e01
update key ACL to r/w
this allows the OS to initialize the keys

note that including write access only gives it to the fw0 user,
which is the OS's secure user. thus any write primitive created
by this expansion of access should transitively also be a read
primitive (which is actually what the adversary desires).

In exchange the OS is allowed to initialize the keys, which
I think is the right place to do it given that it's too hard
at this point to nail down the exact key layout, etc.

Note that it is impossible for the OS to change ACLs - that is
a feature that can only be updated by the boot user - which
is why the boot user can change the ACL to gain access to
erase keys, but the OS user can't modify its own ACL.
2025-11-13 11:06:16 +08:00
bunnie
10bd1502d0 fix ACL to match actual usage of data slots 2025-11-12 22:08:12 +08:00
bunnie
94964f12a2 reduce debug noise 2025-11-12 17:46:38 +08:00