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.
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.
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.
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.
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.
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.
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.
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.
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.
- 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.
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.
- 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).
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
- 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.
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.
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.
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...
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.
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.
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.
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.
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.
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 :-/
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
- 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.
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.
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.).
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.
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.
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.
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.