Public: anyone can read this; the crew can change it.

SSH offers the hybrid post-quantum key exchange first: mlkem768x25519-sha256 #17997

opened this

Merged 14h 41m ago, live in production

sold/ssh-mlkem → main 0 commits 3 threads · 3 unresolved

  • Merged. sold/ssh-mlkem was merged into main as 05c87e1.

Review

Sign in to review this change.
5 files changed +102 −13
docs/OPERATING.md +2
@@ -102,6 +102,8 @@ Unset, no one may say so, this machine included: the socket peer is the client,
102102 instance _is_ lives under the data directory — the SQLite index, the bare
103103 repos, and the SSH host key, in plain layout. Tar it up and it moves.
104104
105 The SSH server offers `mlkem768x25519-sha256` first: ML-KEM-768 with X25519, OpenSSH 9.9's default, so what is recorded today cannot be read by a later quantum computer. Older clients get `curve25519-sha256` (`src/ssh/transport.ts`).
outdated

The new sentence is glued onto the host-key paragraph as one very long line. Put it in its own sentence or paragraph.

106
105107 The SSH host key is `<data>/ssh/host_ed25519`, and the snapshot carries it (`ssh/`), so a restore
106108 keeps the fingerprint people have trusted; lose both and every client sees "host key changed". The key must be mode 0600; a volume's group bits can widen it on every mount, so the forge tightens its own key at start (a key it does not own, or cannot chmod, is refused and the terminal stays off, with the reason logged). The
107109 home page shows the fingerprint beside the ssh command, to compare with what `ssh` prints on
src/ssh/kex.ts +23 −1
@@ -2,7 +2,8 @@
22 * The two pure computations of the key exchange, apart from the transport so
33 * known answers can pin them: the exchange hash H (RFC 4253 §8, with the
44 * curve25519 fields of RFC 8731 §3.1) and key derivation (RFC 4253 §7.2).
5 * Both use SHA-256, the hash of `curve25519-sha256`.
5 * Both use SHA-256, the hash of `curve25519-sha256` and of `mlkem768x25519-sha256`
6 * (draft-ietf-sshm-mlkem-hybrid-kex, OpenSSH 9.9's default), whose K is a string, not an mpint.
67 */
78
89 import { createHash } from "node:crypto";
@@ -61,3 +62,24 @@ export function deriveKey(
6162 }
6263 return new Uint8Array(out.subarray(0, length));
6364 }
65
66 /** The hybrid post-quantum key exchange: ML-KEM-768 (FIPS 203) with X25519. */
67 export const MLKEM_KEX = "mlkem768x25519-sha256";
68 /** An ML-KEM-768 encapsulation key's length; its ciphertext is 1088 bytes, its shared secret 32. */
69 export const MLKEM_PUBLIC = 1184;
70
71 /** The hybrid's K as the exchange hash and the key derivation take it: SHA-256 of the ML-KEM secret then the X25519 one, as an SSH string. */
72 export const hybridK = (mlkemShared: Uint8Array, x25519Shared: Uint8Array): Uint8Array =>
73 sshString(new Uint8Array(createHash("sha256").update(mlkemShared).update(x25519Shared).digest()));
74
75 /** Encapsulate to the client's ML-KEM-768 key (WebCrypto's own, no library): the ciphertext and the shared secret. */
76 export async function mlkemEncapsulate(publicKey: Uint8Array): Promise<{ ciphertext: Uint8Array; sharedKey: Uint8Array }> {
77 // WebCrypto's ML-KEM is newer than the DOM types this repository builds with.
78 const subtle = crypto.subtle as unknown as {
79 importKey(f: "raw-public", k: Uint8Array, a: { name: string }, x: boolean, u: string[]): Promise<CryptoKey>;
80 encapsulateBits(a: { name: string }, k: CryptoKey): Promise<{ ciphertext: ArrayBuffer; sharedKey: ArrayBuffer }>;
81 };
82 const key = await subtle.importKey("raw-public", publicKey, { name: "ML-KEM-768" }, false, ["encapsulateBits"]);
83 const out = await subtle.encapsulateBits({ name: "ML-KEM-768" }, key);
84 return { ciphertext: new Uint8Array(out.ciphertext), sharedKey: new Uint8Array(out.sharedKey) };
85 }
src/ssh/transport.ts +41 −7
@@ -18,7 +18,7 @@ import {
1818 randomFillSync,
1919 } from "node:crypto";
2020 import type { Log } from "../kernel/log.ts";
21 import { deriveKey, exchangeHashOf } from "./kex.ts";
21 import { deriveKey, exchangeHashOf, hybridK, MLKEM_KEX, MLKEM_PUBLIC, mlkemEncapsulate } from "./kex.ts";
2222 import { type HostKey, SERVER_SIG_ALGS, signWithHostKey } from "./keys.ts";
2323 import {
2424 ByteQueue,
@@ -42,9 +42,10 @@ const MAX_PACKET_PLAINTEXT = 35000;
4242 const MAX_VERSION_LINE = 255;
4343 const MAX_VERSION_DISCARD = 1024;
4444
45 /** Real key exchange methods, in our preference order. Identical behaviour;
46 * the `@libssh.org` name simply predates standardisation. */
47 const KEX_ALGORITHMS = ["curve25519-sha256", "curve25519-sha256@libssh.org"];
45 /** Real key exchange methods, in our preference order. The hybrid one first: ML-KEM-768 with X25519
46 * resists a later quantum computer reading what is recorded today, as OpenSSH 9.9 and later offer
47 * it first. curve25519 stays for older clients; its `@libssh.org` name predates standardisation. */
48 const KEX_ALGORITHMS = [MLKEM_KEX, "curve25519-sha256", "[email protected]"];
outdated

Two doc comments are stacked on one constant; the previous one (line 46) is now orphaned. Merge into one block.

4849 const HOST_KEY_ALGORITHMS = ["ssh-ed25519"];
4950 const CIPHERS = ["[email protected]", "[email protected]"];
5051 /** Advertised but ignored: under GCM, MAC negotiation is skipped entirely
@@ -160,7 +161,7 @@ export class Transport {
160161 * Never rebuild these — a re-serialised KEXINIT gives a wrong H. */
161162 private myKexInit: Uint8Array | undefined;
162163 private peerKexInit: Uint8Array | undefined;
163 private negotiated: { cipherIn: string; cipherOut: string } | undefined;
164 private negotiated: { kex: string; cipherIn: string; cipherOut: string } | undefined;
164165
165166 /** Outbound payloads parked while a key exchange is in flight (RFC 4253 §9
166167 * forbids non-KEX traffic between our KEXINIT and our NEWKEYS). */
@@ -596,7 +597,7 @@ export class Transport {
596597 this.disconnect(DISCONNECT.KEY_EXCHANGE_FAILED, "no common algorithm");
597598 return;
598599 }
599 this.negotiated = { cipherIn: selectedIn, cipherOut: selectedOut };
600 this.negotiated = { kex, cipherIn: selectedIn, cipherOut: selectedOut };
600601
601602 // first_kex_packet_follows: the peer already sent its guessed KEX packet.
602603 // The guess is judged on its *literal* first entries; if wrong, the next
@@ -624,12 +625,37 @@ export class Transport {
624625 r.u8();
625626 const clientPublic = r.string();
626627 r.end();
628 // mlkem768x25519-sha256 sends the ML-KEM public key, then the X25519 one.
629 if (this.negotiated.kex === MLKEM_KEX) {
630 if (clientPublic.length !== MLKEM_PUBLIC + 32) {
631 this.disconnect(DISCONNECT.KEY_EXCHANGE_FAILED, "bad C_INIT length");
632 return;
633 }
634 const x = this.x25519(clientPublic.subarray(MLKEM_PUBLIC));
635 if (x === undefined) return;
636 // WebCrypto's ML-KEM answers in a promise; nothing else may run in a key exchange until this reply.
637 void mlkemEncapsulate(clientPublic.subarray(0, MLKEM_PUBLIC)).then(
638 (pq) => {
639 if (this.dead) return;
640 this.finishKex(clientPublic, new Uint8Array(Buffer.concat([pq.ciphertext, x.serverPublic])), hybridK(pq.sharedKey, x.shared));
641 },
642 () => this.disconnect(DISCONNECT.KEY_EXCHANGE_FAILED, "invalid ML-KEM key"),
643 );
644 return;
645 }
627646 // curve25519-sha256 carries the raw 32-byte u-coordinate, not a SEC1 point.
628647 if (clientPublic.length !== 32) {
629648 this.disconnect(DISCONNECT.KEY_EXCHANGE_FAILED, "bad Q_C length");
630649 return;
631650 }
632651
652 const x = this.x25519(clientPublic);
653 if (x === undefined) return;
654 this.finishKex(clientPublic, x.serverPublic, new Writer(48).mpint(x.shared).build());
655 }
656
657 /** One X25519 half: our ephemeral public key and the shared secret, or undefined after a disconnect. */
658 private x25519(clientPublic: Uint8Array): { serverPublic: Uint8Array; shared: Buffer } | undefined {
633659 const ephemeral = generateKeyPairSync("x25519");
634660 // SPKI for X25519 is a fixed 12-byte prefix then the 32-byte key.
635661 const spki = ephemeral.publicKey.export({ type: "spki", format: "der" });
@@ -660,8 +686,16 @@ export class Transport {
660686 return;
661687 }
662688
689 return { serverPublic, shared };
690 }
691
692 /**
693 * The end of every key exchange: the exchange hash over Q_C, Q_S and K as the method encodes it
694 * (an mpint for curve25519, a string for the hybrid), the signed reply, the keys and NEWKEYS.
695 */
696 private finishKex(clientPublic: Uint8Array, serverPublic: Uint8Array, kMpint: Uint8Array): void {
697 if (this.negotiated === undefined) return;
663698 const hostBlob = this.options.hostKey.publicKey.blob;
664 const kMpint = new Writer(48).mpint(shared).build();
665699 const exchangeHash = exchangeHashOf({
666700 clientVersion: this.clientVersion ?? new Uint8Array(0),
667701 serverVersion: this.serverVersion,
test/git-ssh.test.ts +15 −4
@@ -42,6 +42,8 @@ quietLogs();
4242 const SSH_KEYGEN = "/usr/bin/ssh-keygen";
4343 /** The client half is the real OpenSSH; without it these skip, loudly. */
4444 const NO_OPENSSH = missing("/usr/bin/ssh", SSH_KEYGEN);
45 /** OpenSSH 9.9 and later name the hybrid post-quantum exchange; an older client cannot ask for it. */
46 const HYBRID_KEX = !NO_OPENSSH && Bun.spawnSync(["/usr/bin/ssh", "-Q", "kex"]).stdout.toString().split("\n").includes("mlkem768x25519-sha256");
4547
4648 interface Run {
4749 code: number;
@@ -59,9 +61,9 @@ describe.skipIf(NO_OPENSSH)("git over ssh", () => {
5961 let alice: User;
6062 let bob: User;
6163
62 const env = (key: string): Record<string, string> =>
64 const env = (key: string, kex = ""): Record<string, string> =>
6365 gitClientEnv({
64 GIT_SSH_COMMAND: `/usr/bin/ssh -i ${key} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o BatchMode=yes -o LogLevel=ERROR -o ConnectTimeout=5`,
66 GIT_SSH_COMMAND: `/usr/bin/ssh -i ${key} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o BatchMode=yes -o LogLevel=ERROR -o ConnectTimeout=5${kex === "" ? "" : ` -o KexAlgorithms=${kex}`}`,
6567 GIT_AUTHOR_NAME: "Tester",
6668 GIT_AUTHOR_EMAIL: "[email protected]",
6769 GIT_COMMITTER_NAME: "Tester",
@@ -71,11 +73,11 @@ describe.skipIf(NO_OPENSSH)("git over ssh", () => {
7173 /** `git push` is blocked at the shell level, so every client call spawns. */
7274 async function git(
7375 args: string[],
74 o: { cwd: string; key: string },
76 o: { cwd: string; key: string; kex?: string },
7577 ): Promise<Run> {
7678 const proc = Bun.spawn(["git", ...args], {
7779 cwd: o.cwd,
78 env: env(o.key),
80 env: env(o.key, o.kex),
7981 stdout: "pipe",
8082 stderr: "pipe",
8183 });
@@ -171,6 +173,15 @@ describe.skipIf(NO_OPENSSH)("git over ssh", () => {
171173 ).toContain("Beacon");
172174 });
outdated

Fails on OpenSSH older than 9.9. Skip the mlkem case when ssh -Q kex does not list mlkem768x25519-sha256, and add a known-answer test for the hybrid K/H encoding in the kex unit tests.

173175
176 test("a client asking only for the hybrid post-quantum key exchange gets it; one asking only for curve25519 still does", async () => {
177 const kexes = HYBRID_KEX ? ([["mlkem768x25519-sha256", "pq-beacon"], ["curve25519-sha256", "classic-beacon"]] as const) : ([["curve25519-sha256", "classic-beacon"]] as const);
178 for (const [kex, dir] of kexes) {
179 const run = await git(["clone", url("alice", "beacon"), dir], { cwd: work, key: strangerKey, kex });
180 expect(run.code).toBe(0);
181 expect(await readFile(join(work, dir, "README.md"), "utf8")).toContain("Beacon");
182 }
183 });
184
174185 test("a guest cannot clone a private repo, and is told nothing else", async () => {
175186 const run = await git(["clone", url("alice", "vault"), "guest-vault"], {
176187 cwd: work,
test/ssh-known-answers.test.ts +21 −1
@@ -7,7 +7,7 @@
77
88 import { expect, test } from "bun:test";
99 import { createPublicKey, createPrivateKey, diffieHellman } from "node:crypto";
10 import { deriveKey, exchangeHashOf } from "../src/ssh/kex.ts";
10 import { deriveKey, exchangeHashOf, hybridK, MLKEM_PUBLIC, mlkemEncapsulate } from "../src/ssh/kex.ts";
1111 import { fingerprintOf } from "../src/ssh/keys.ts";
1212 import { sshString, Writer } from "../src/ssh/wire.ts";
1313
@@ -77,3 +77,23 @@ test("a fingerprint is SHA256: and unpadded base64 of the blob", () => {
7777 const blob = sshString("ssh-ed25519");
7878 expect(fingerprintOf(blob)).toBe("SHA256:" + new Bun.CryptoHasher("sha256").update(blob).digest("base64").replace(/=+$/, ""));
7979 });
80
81 test("the hybrid's K is SHA-256 of the ML-KEM secret then the X25519 one, as an SSH string", () => {
82 const k = hybridK(new Uint8Array(32).fill(1), new Uint8Array(32).fill(2));
83 expect(Buffer.from(k).toString("hex")).toBe("00000020f818afd37a6dc3bc92fb44731011277006db4efa6e9023cd7468c02335d22a4d");
84 });
85
86 test("ML-KEM-768 as the transport encapsulates: the client's decapsulation gets the same secret", async () => {
87 const subtle = crypto.subtle as unknown as {
88 generateKey(a: { name: string }, x: boolean, u: string[]): Promise<CryptoKeyPair>;
89 exportKey(f: "raw-public", k: CryptoKey): Promise<ArrayBuffer>;
90 decapsulateBits(a: { name: string }, k: CryptoKey, c: Uint8Array): Promise<ArrayBuffer>;
91 };
92 const pair = await subtle.generateKey({ name: "ML-KEM-768" }, true, ["encapsulateBits", "decapsulateBits"]);
93 const pub = new Uint8Array(await subtle.exportKey("raw-public", pair.publicKey));
94 expect(pub.length).toBe(MLKEM_PUBLIC);
95 const out = await mlkemEncapsulate(pub);
96 expect(out.ciphertext.length).toBe(1088);
97 expect(Buffer.from(await subtle.decapsulateBits({ name: "ML-KEM-768" }, pair.privateKey, out.ciphertext)).equals(Buffer.from(out.sharedKey))).toBe(true);
98 await expect(mlkemEncapsulate(pub.subarray(1))).rejects.toThrow();
99 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs