Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 18 min read

I tried to prove my secret-sharing tool correct in Lean 4. The proof found an attack.

I'm taking a cryptography course in my master's degree this semester. When we reached AES, we had to learn Galois fields: a strange kind of arithmetic where a byte plus itself is zero, and multiplication is done "modulo

I tried to prove my secret-sharing tool correct in Lean 4. The proof found an attack.

I'm taking a cryptography course in my master's degree this semester. When we reached AES, we had to learn Galois fields: a strange kind of arithmetic where a byte plus itself is zero, and multiplication is done "modulo a polynomial". In class it is one step inside AES.

The same field is the heart of a project I have been building: qedshare, a small command-line tool for Shamir's Secret Sharing, written in Lean 4. What makes it different from other tools is that its important properties are mathematical theorems checked by a computer, not just tests.

I'll explain the idea in simple terms first, then show how the proofs are built, and at the end I'll list what is still not proven.

GitHub logo KhaledSaeed18 / qedshare

Formally verified Shamir's Secret Sharing CLI in Lean 4 over GF(2^8). Reconstruction correctness and perfect secrecy are theorems checked by Lean; branch-free, table-free field arithmetic.

qedshare

Shamir's Secret Sharing, with the important parts proven in Lean 4.

Pronounced "Q-E-D share". Q.E.D. is how a proof ends.

CI API docs Release Lean sorry Axiom audit License

Quick start Β· How it works Β· Guarantees Β· Word shares Β· Threat model Β· API docs

Split a secret (a password-manager master key, an SSH key, a wallet seed) into n shares so that any k shares rebuild it and any k βˆ’ 1 shares reveal nothing at all. qedshare is a small command-line tool whose key properties are theorems checked by Lean's kernel, about the exact code the executable runs, not just tests.

Warning

Early development, not audited. The CLI works and every guarantee below is proven (zero sorry; CI fails on any). Do not use it for real secrets yet.

Contents

TL;DR

  • Split a secret into n shares. Any k of them rebuild it. Any k βˆ’ 1 reveal nothing.
  • "It rebuilds the secret", "fewer shares reveal nothing" and "forged shares are refused" are proven for every input, and Lean checks the proofs on every build.
  • One proof attempt failed, and the reason was a real attack. The fix is proven too.
  • Not proven: file handling, the OS random number generator, the compiler, timing. A normal review found real bugs there.
  • It is not audited. Please don't use it for real secrets yet.

The problem

You have one very important secret, for example the master password of your password manager. You have two fears:

  • Losing it. With one copy, a lost copy means the secret is gone.
  • Someone stealing it. With many copies, any stolen copy gives everything away.

Secret sharing solves both. You cut the secret into pieces called shares and you choose two numbers:

  • n: how many shares to make (say 5),
  • k: how many are needed to rebuild the secret (say 3).

Any 3 of the 5 shares rebuild the secret, so you can lose 2. Someone who holds only 2 learns nothing at all. Not "very little". Nothing.

The idea, with a line

A blue thread pulled tight between two brass pins on a sheet of paper

Think of a straight line on paper. One point is not enough to know the line, because infinitely many lines pass through it. Two points fix it exactly.

So for "any 2 shares rebuild it":

  1. Put the secret where the line crosses the vertical axis (at x = 0).
  2. Draw a random line through that point.
  3. Give each person one other point on the line: (1, f(1)), (2, f(2)), and so on.

Two people together can redraw the line and read the secret. One person alone has one point, and every possible secret still fits it.

For k = 3 you use a curve that needs 3 points (f(x) = s + r₁·x + rβ‚‚Β·xΒ²), and so on. Rebuilding the curve from its points is called Lagrange interpolation. Longer secrets are split one byte at a time, each byte with its own random curve.

This is Adi Shamir's scheme from 1979. It fits on a napkin.

Where my course comes in

Normal numbers don't work well here, because they grow without limit and division gives fractions. Shamir's scheme needs a finite field: a fixed set of values where you can add, subtract, multiply and divide, and always stay inside the set.

qedshare uses GF(2⁸), the same 256-element field as AES:

  • every byte is one element,
  • addition is XOR, so a + a = 0 and subtraction is the same as addition,
  • multiplication is polynomial multiplication modulo x⁸ + x⁴ + xΒ³ + x + 1 (0x11B), the AES polynomial,
  • every nonzero byte has an inverse, which is what makes the division in Lagrange interpolation possible.

Several other things from the course show up too:

In the course In qedshare
Galois fields (the AES chapter) All the arithmetic is in GF(2⁸) with the AES polynomial
The one-time pad, the "unbreakable" cipher Shamir has the same kind of security: perfect, not "hard to break"
Random numbers The curve must be truly random, like one-time pad key bytes
Modular inverses and fast exponentiation The inverse of a byte is a²⁡⁴, computed by squaring and multiplying
GMAC, authentication in GF(2¹²⁸) Forged shares are caught with a tag in GF(2¹²⁸)

Secret sharing itself is not in our textbook, but it is built from the same maths.

Using it

Split a secret into 5 shares, where any 3 rebuild it:

$ printf 'correct horse battery staple\n' > secret.txt
$ qedshare split --threshold 3 --shares 5 < secret.txt > shares.txt
$ cut -c1-60 shares.txt
qs3-f0a935f0-03-01-7dc2c3608c0d11908d1ebcceb19ed816248022835
qs3-f0a935f0-03-02-14b4e934a1b86263c6a68e6ff3647cf916e48a326
qs3-f0a935f0-03-03-0a19582648d607d323d740d227dac68e4610cdc34
qs3-f0a935f0-03-04-ba9cfa6dc2d20546c84a66a4c624818995d83f201
qs3-f0a935f0-03-05-a4314b7f2bbc60f62d3ba819129a3bfec52c78d13

Give each line to a different person or place. To get the secret back, give any 3 of them to combine:

$ sed -n '1p;4p;5p' shares.txt | qedshare combine
correct horse battery staple

$ sed -n '1p;4p' shares.txt | qedshare combine
qedshare: error: this secret needs 3 shares, but only 2 were given

A long hex string is fine for copy-paste and awful for a pen. So --words writes each share as ordinary English words that you can write on paper:

$ printf 'send 100 to bob' | qedshare split -k 2 -n 3 --words
acquire rifle oblige ring cactus oak supreme solar charge casino hotel social be…

Hex shares and word shares can be mixed in one combine. (Word shares use the BIP-39 word list from crypto wallets, but they are not wallet seed phrases. Only the list is borrowed.)

Two more commands look at shares without showing the secret:

$ sed -n '1p;4p;5p' shares.txt | qedshare verify
ok: the 3 shares fit together and rebuild a secret of 29 bytes

$ sed -n '1p;4p' shares.txt | qedshare info
stdin line 1: qs3 hex share, set f0a935f0, index 1, threshold 3, secret of 29 bytes
stdin line 2: qs3 hex share, set f0a935f0, index 4, threshold 3, secret of 29 bytes
2 different shares of set f0a935f0: 1 more needed to rebuild the secret (threshold 3)

The secret is only ever read from stdin or a file, never from the command line, where it would end up in your shell history. Install steps are in the quick start.

Why proofs, when the maths is this simple?

Because implementations still get it wrong, in small ways that matter a lot. Some classic bugs:

  • Handing out the share at x = 0. That point is the secret.
  • Forcing the top random coefficient to be nonzero. It sounds like harmless hygiene ("make sure the curve really has degree k βˆ’ 1"). It quietly breaks secrecy: with k βˆ’ 1 shares, some secrets become more likely than others.
  • Accepting duplicate shares, or shares from two different splits.
  • Using normal + and * on bytes where field operations were meant. The code runs, the output looks fine, and it is wrong.
  • Multiplying with lookup tables on secret data, which can leak through cache timing.

A test tries examples: "I split this secret, combined it, and got it back, 1,000 times." It says nothing about the cases you did not try.

A proof covers every case at once: every secret, every k and n, every random choice. It is like school geometry. You don't measure a million triangles to know the angles add up to 180Β°. You prove it once.

Lean in one minute

Lean 4 is two things in one language:

  1. A normal programming language. You write functions and compile them to a native program. The whole tool is written in it.
  2. A proof checker. In the same file you write a claim about your function and a proof of it. Lean checks every step. If one step is wrong or missing, the file does not compile.

I'm mostly a TypeScript developer, so I think of it as a much stronger type checker. TypeScript can check "this function returns a string". Lean can check "this function returns the original secret, for every possible input".

Lean has a word for "I will prove this later": sorry. This repo has zero of them, and the build fails if one appears.

The one design rule that makes it provable

The most important decision is not a proof. Randomness is an argument, not an effect:

/-- Split `secret` into `p.n` shares with threshold `p.k`, using the random coefficients `rand`
(one list of `k βˆ’ 1` coefficients per secret byte). -/
def split (p : Params) (secret : List GF256) (rand : List Poly) :
    Except SplitError (List Share) :=
  if ValidRand p secret.length rand then
    .ok ((indices p.n).map (shareAt secret rand))
  else
    .error .badRandomness

The core library never asks the operating system for random bytes. It receives them as input. Only a thin outer layer reads files and the OS random number generator. Because of this, a theorem can say "for every possible randomness…", and that is exactly the shape a secrecy statement needs.

Field β†’ Poly β†’ Shamir β†’ Encoding β†’ CLI      (the tool, no heavy dependencies)
                                    ↑
                  proofs/  (separate package, uses Mathlib, Lean's maths library)

What is proven

1. The careful multiply equals the textbook multiply

A field element is its own type, not a plain byte, so the compiler will not let normal + and * leak in:

structure GF256 where
  val : UInt8

The textbook multiply is easy to read, but it has an if on its input bits, and that can leak secret data through timing. The version the tool runs has no branches and no lookup tables. It replaces each if with a mask that is 0x00 or 0xFF.

So there are two functions, a simple one and a careful one, and a theorem that they are the same:

/-- The constant-time byte multiply equals the textbook byte multiply, for every input. -/
theorem mulByte_eq_mulSpecByte (a b : UInt8) : mulByte a b = mulSpecByte a b := by
  simp only [mulByte, mulSpecByte, xtime, xtimeSpec, mask, bitSet]
  bv_decide

bv_decide hands the question to a SAT solver, and Lean then checks the solver's certificate. That covers all 65,536 input pairs in one step.

I use this pattern everywhere in the project: a simple version, a fast version, and a theorem that they agree. I think about the simple one, and the machine runs the fast one.

One fun detail: the solver timed out on (a Β· b) Β· c = a Β· (b Β· c). The fix was a little algebra first. Every byte is the XOR of its 8 single bits, and multiplication is linear over XOR, so it is enough to prove the law when a has one bit set. That is a much smaller problem. Automation does the dull part, and the maths gives it the right shape.

2. Any k shares rebuild the secret

/-- Any `k` or more shares with distinct indices, taken from one successful `split`,
make `combine` return exactly the secret. -/
theorem combine_split {p : Params} {secret : List GF256} {rand : List Poly}
    {shares chosen : List Share} (h : split p secret rand = .ok shares)
    (hsub : βˆ€ sh ∈ chosen, sh ∈ shares) (hnd : (chosen.map (Β·.x)).Nodup)
    (hk : p.k ≀ chosen.length) :
    combine p.k chosen = .ok secret

Read what it covers: any parameters, any secret, any randomness, and any choice of at least k different shares.

The key fact, "a curve of degree below k is fixed by k of its points", already exists in Mathlib, Lean's large maths library. Mathlib is several GB to build, so it lives in a separate proofs/ package. People who only want the tool never download it.

Rejecting bad input is proven too: too few shares, duplicate shares, and a share at x = 0 are all refused.

3. Fewer than k shares reveal nothing

This is my favourite part. "Reveals nothing" becomes a precise claim:

Take any k βˆ’ 1 shares and any two secrets of the same length. There is a one-to-one matching between the random choices, such that each random choice for the first secret gives exactly the same shares as its partner does for the second secret.

So whatever k βˆ’ 1 shares you are looking at, exactly as many random choices produce them from one secret as from any other. Every secret is equally likely. This is the same kind of security as the one-time pad.

The matching is simple: add to the curve a second curve that is zero at the shares you hold and nonzero at x = 0. Your shares do not change, but the secret does. Adding it twice cancels out (in this field a + a = 0), so the matching is its own inverse.

There is a nice payoff. Remember the "force the top coefficient to be nonzero" bug? A split with that bug cannot satisfy this theorem, because the theorem is about all randomness. The whole class of bug is ruled out.

(Credit: the same idea appears in Vocdoni's masked Shamir shares formalization over an abstract field. qedshare applies it to the concrete byte-level code that runs.)

4. Forged shares are refused

Five brass keys in a row, one of them a different shape

Shamir's scheme assumes people hand back the shares they were given. What if one person changes theirs on purpose?

The maths is linear, so a cheater can shift the rebuilt secret by any amount they like without knowing the secret. A checksum does not help, because they recompute it. A script in the repo does exactly this against an unprotected format: the secret was "send 100 to bob" and combine happily returned "send 900 to bob".

The simple fix: bring one extra share. With k + 1 shares, combine rebuilds the curve from k of them and checks that the others lie on it. A forged share is always refused (combine_detects_forgery). There is no probability and no hardness assumption involved. With k + 2 or more, the tool also names the bad share:

$ qedshare combine forged.txt share-2.txt share-3.txt share-4.txt
qedshare: error: the shares do not all fit together: forged.txt is the odd one out (the other 3 agree with each other), so it is probably wrong or forged

With exactly k shares there is nothing extra to compare against. So before splitting, the tool adds a random key and a tag computed from the secret and the key, in the larger field GF(2¹²⁸). This is called an AMD code (Cramer, Dodis, Fehr, Padró and Wichs, 2008). After rebuilding, combine recomputes the tag and refuses on a mismatch. The cheaters never see the key, so they have to guess. For a 1 MiB secret their chance is about 2⁻¹¹².

Two details I enjoyed:

  • Building GF(2¹²⁸). GMAC uses this field too, but I built it differently: as a tower on top of our GF(2⁸), in four steps, where each step doubles the number of bytes (1 β†’ 2 β†’ 4 β†’ 8 β†’ 16). It reuses the careful byte multiply, so there are still no tables and no branches.
  • The textbook parameter was wrong for this use. A cheater can also change a share's index, which is just a number in the share text. The textbook analysis does not cover that. With the textbook setting, I found a change that passed the check for all 4,096 keys I tried. A different choice of one parameter fixes it, and that is proven (amd_detect).

5. The proof that found a hole

My plan said: "with exactly k shares, the tag catches every forgery." I had 3,000 random simulations that agreed.

Then I tried to prove it, and the proof would not go through. To finish it, I had to compute one quantity exactly, and it turned out the cheaters could choose the index of their forged share so that the honest shares cancel out. The rebuilt result then does not depend on the real secret at all, and they can replace it with any secret they like, with a valid tag.

Random simulations almost never pick that index. An attacker picks it on purpose. I wrote the attack, ran it against the real program, and combine printed attacker chosen! with a success exit code.

So the first version of the theorem had an honest extra condition, and the README said exactly what held and what did not.

The fix: a token on every share. split now draws one more random curve G and gives share i a 16-byte token G(i). combine rebuilds G and checks every share's token. The cheaters hold k βˆ’ 1 values of G, and that is one too few to predict it anywhere else:

  • If they cancel the honest shares, the honest tokens no longer fit.
  • If they forge a share at an index they do not hold, they need a token they cannot predict.
  • If they only use indices they hold, the tag from before catches them.

The final theorem (combine_detects_forgery_tok) has no conditions left: any forging strategy, any number of honest shares, any indices. Every forgery is refused except with probability about 2⁻¹¹² for a 1 MiB secret. A companion theorem shows the tokens leak nothing about the secret. The attack still runs in CI on every push, and now it has to fail.

One more condition was hiding: the theorem had the honest shares first in the list. So there is a theorem that combine gives the same answer for every order of the shares (combine_perm).

(I had first planned Feldman verifiable secret sharing here. I dropped it: it needs a whole new primitive, it weakens perfect secrecy for low-entropy secrets, and it protects against a cheating dealer, while here the dealer is you.)

6. The program around the maths

"The core is proven" says little if the glue around it is wrong. So the glue is split in two: pure functions from text to text, and a thin part that only reads and writes. The pure part has its own theorems:

  • Every share that split writes, in hex or in words, reads back to the same share.
  • Whatever split prints, combine on any k or more of those lines, in any order, returns exactly the secret (recoverSecret_makeShares).
  • When combine accepts, its answer is exactly what the proven core computes, so the forgery guarantees apply to the real program.

The proofs like simple lists, and the machine does not. A 1 MiB secret with threshold 20 needed 1.3 GB of memory to split. I did not rewrite the proven code. I used the same pattern as the multiply: a second, memory-light version on byte arrays, and a theorem that both compute the same thing. Memory went from 1.3 GB to 300 MB for splitting and from 714 MB to 41 MB for combining, and no existing theorem was touched.

What the proofs did not find

Before one release I reviewed the whole tool the ordinary way. Every bug was in the part with no theorems:

  • split --out-dir created each share file with default access rights and narrowed them afterwards, so a share was briefly readable by other users.
  • If writing the share files failed halfway, the files already written stayed behind.
  • A byte-order mark at the start of a file made the first share unreadable.
  • --shares 1_0 was read as 10, and a repeated option silently took the last value.

None of these contradicts a theorem. Proofs move the bugs to where the proofs are not, and that is where review and tests have to look.

What you still have to trust

A proof is only as good as what it rests on. The repo has an axiom audit: a file that prints the assumptions behind every headline theorem and fails the build if anything unexpected appears.

QedShare.Shamir.combine_split: [propext, Classical.choice, Quot.sound] + 10 bv_decide certificate check(s)
QedShare.Shamir.perfect_secrecy_card: [propext, Classical.choice, Quot.sound] + 11 bv_decide certificate check(s)
QedShare.Shamir.combine_detects_forgery_tok: [propext, Classical.choice, Quot.sound] + 11 bv_decide certificate check(s)

The three names are Lean's standard axioms, used all through Mathlib. Each bv_decide step adds one more: "Lean's compiled checker accepted the SAT solver's certificate."

What is not proven:

  • File handling and argument parsing. Tested on Linux and macOS, not proven.
  • The OS random number generator. The theorems assume the randomness is uniform. They cannot check that it is.
  • The Lean compiler and the C toolchain.
  • Timing. The multiply has no branches and no table lookups, but "constant time" is a property of the final machine code, and that is not proven.
  • Naming the bad share when there are several. With exactly one bad share the name is proven right. With two or more it is a hint.
  • Old qs2 shares still have the hole from section 5 when you bring exactly k shares. New shares are qs3.
  • It has not been audited. Please do not use it for real secrets yet.

The full list, with theorem names, is in the README under Guarantees and Threat model.

Will the shares still work in ten years?

A share is only useful if a later version of the tool can still read it. So since v0.18.0 the qs3 share format is frozen: every later version will read qs3 shares, in hex and in words. Any change to what split writes gets a new name (qs4), and qs3 stays readable.

This is a promise, not a theorem. It is held by tests: fixed shares sit in the test suite, and on every push split must write exactly those strings and combine must read them back.

What I learned

  • Design for the proof before writing the code. Passing randomness in as an argument cost almost nothing. Without it, the main theorems could not even be stated.
  • Simple version + fast version + a theorem that they agree is a great pattern. It worked for a one-byte multiply and for the whole program's memory use.
  • Automation needs the right shape. The SAT solver proves 16-bit facts at once and times out on 24-bit ones. A little algebra fixed it.
  • A proof attempt is a very thorough code review. 3,000 random simulations said the plan was fine. The proof found the attack.
  • Read the theorem, not its name. Twice my README said a little more than the Lean statement did. Checking them line by line found both.
  • Proofs move the bugs. After the core was proven, every bug was in file handling and argument parsing.
  • Be honest about what is trusted. "Formally verified" means nothing without saying what is verified.

Links

If you are learning cryptography, try building one small thing from your course and proving one fact about it. The proofs are hard in a satisfying way, and when the build goes green you know something, instead of hoping your tests were thorough enough.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.