1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+238
View File
@@ -0,0 +1,238 @@
; ============================================================================
; BakaShrot Cipher
;
; Encrypts and authenticates buffers with a shared key, and checks and
; decrypts them, so the rest of the code never touches the crypto: give it
; a key once, then hand it buffers.
;
; Cipher.BakaShrot_Cipher
; BakaShrot_Cipher_Init(@Cipher, *Key, #BakaShrot_Cipher_Client)
; *Sealed = BakaShrot_Cipher_Encrypt(@Cipher, *Packet, PacketSize, @SealedSize)
; ... send it, and on the other end, with a cipher for #BakaShrot_Cipher_Server:
; *Packet = BakaShrot_Cipher_Decrypt(@Cipher, *Sealed, SealedSize, @PacketSize)
; If Not *Packet : abort the connection : EndIf
; BakaShrot_Cipher_Clear(@Cipher) once done, wipes the keys.
;
; What it guarantees, for buffers sent in order over one connection (TCP):
; - Nobody without the key can read them (XChaCha20).
; - Nobody without the key can change, forge or truncate one (Poly1305):
; decrypting it fails.
; - Nobody can replay, reorder, drop or reflect one: each buffer carries
; its sequence number, the receiver only takes the next one it expects,
; and each direction encrypts under its own nonces (or its own key), so
; a buffer sent back to its sender doesn't decrypt either.
; Any failure means the stream can't be trusted anymore: abort the
; connection, don't try the next buffer.
;
; What it doesn't do: get the key. Both ends must already share it, agreed
; on for this connection only (Session.pbi does it for the handshake), never
; a key reused across connections: the sequence numbers start over at 0.
;
; A sealed buffer is:
; [sequence number, 8 bytes, little-endian][encrypted data][tag, 16 bytes]
; #BakaShrot_Cipher_Overhead bytes more than the data. The nonce (24 bytes)
; is the direction (1 byte), zeros, then the sequence number, never sent.
; The sequence number is authenticated too (additional data).
;
; libsodium's crypto_aead_xchacha20poly1305_ietf_*, imported in
; Libsodium.pbi: nothing here implements a primitive. InitCryptography()
; must have been called.
;
; Threads: encrypting and decrypting use separate state, so one thread may
; send while another receives. Two threads must not encrypt (or decrypt)
; with the same cipher at once.
; ============================================================================
XIncludeFile "Libsodium.pbi"
#BakaShrot_Cipher_KeySize = #BakaShrot_XChaCha20Poly1305_KeySize
#BakaShrot_Cipher_SequenceSize = 8
#BakaShrot_Cipher_Overhead = #BakaShrot_Cipher_SequenceSize + #BakaShrot_XChaCha20Poly1305_TagSize
; Which end of the connection a cipher is on, when both share one key: each
; encrypts under its own nonces. Never 0.
#BakaShrot_Cipher_Client = 1
#BakaShrot_Cipher_Server = 2
; Past this many buffers in one direction, encrypting refuses: never reached
; in practice (2^63), but a sequence number must never wrap around.
#BakaShrot_Cipher_MaxSequence = $7FFFFFFFFFFFFFFF
Structure BakaShrot_CipherNonce
Bytes.a[#BakaShrot_XChaCha20Poly1305_NonceSize]
EndStructure
Structure BakaShrot_Cipher
SendKey.a[#BakaShrot_Cipher_KeySize]
ReceiveKey.a[#BakaShrot_Cipher_KeySize]
; First byte of the nonces of each direction.
SendDirection.a
ReceiveDirection.a
; Sequence number of the next buffer to send, and of the next one
; expected.
SendSequence.q
ReceiveSequence.q
IsReady.l
EndStructure
; Fills *Key (#BakaShrot_Cipher_KeySize bytes) with a new random key.
Procedure BakaShrot_Cipher_GenerateKey(*Key)
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
EndProcedure
; Wipes *Cipher's keys and state, it refuses everything until initialized
; again. Call it once the connection is over.
Procedure BakaShrot_Cipher_Clear(*Cipher.BakaShrot_Cipher)
sodium_memzero(*Cipher, SizeOf(BakaShrot_Cipher))
EndProcedure
; Sets *Cipher up with one key shared by both ends (*Key,
; #BakaShrot_Cipher_KeySize bytes, copied), Role being which end this is:
; #BakaShrot_Cipher_Client or #BakaShrot_Cipher_Server, the other end must
; take the other one.
; Returns #False if Role isn't one of them.
Procedure.i BakaShrot_Cipher_Init(*Cipher.BakaShrot_Cipher, *Key, Role.i)
BakaShrot_Cipher_Clear(*Cipher)
If Not *Key Or (Role <> #BakaShrot_Cipher_Client And Role <> #BakaShrot_Cipher_Server)
ProcedureReturn #False
EndIf
CopyMemory(*Key, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*Key, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
*Cipher\SendDirection = Role
If Role = #BakaShrot_Cipher_Client
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Server
Else
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Client
EndIf
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; Sets *Cipher up with a key per direction (each #BakaShrot_Cipher_KeySize
; bytes, copied), like libsodium's crypto_kx_* gives: the other end's
; *SendKey is this one's *ReceiveKey.
; Returns #False if they're the same key: the two directions would then
; encrypt under the same nonces, use BakaShrot_Cipher_Init() for one key.
Procedure.i BakaShrot_Cipher_InitWithKeys(*Cipher.BakaShrot_Cipher, *SendKey, *ReceiveKey)
BakaShrot_Cipher_Clear(*Cipher)
If Not *SendKey Or Not *ReceiveKey Or CompareMemory(*SendKey, *ReceiveKey, #BakaShrot_Cipher_KeySize)
ProcedureReturn #False
EndIf
CopyMemory(*SendKey, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*ReceiveKey, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
; Different keys already keep the directions apart.
*Cipher\SendDirection = 0
*Cipher\ReceiveDirection = 0
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; The nonce of the buffer with that direction and sequence number.
Procedure BakaShrot_Cipher_MakeNonce(*Nonce.BakaShrot_CipherNonce, Direction.a, Sequence.q)
FillMemory(*Nonce, #BakaShrot_XChaCha20Poly1305_NonceSize, 0)
*Nonce\Bytes[0] = Direction
PokeQ(@*Nonce\Bytes[#BakaShrot_XChaCha20Poly1305_NonceSize - 8], Sequence)
EndProcedure
; Encrypts and authenticates *Data (Size bytes, may be 0) into *Sealed,
; which must have room for Size + #BakaShrot_Cipher_Overhead bytes and not
; overlap *Data. *Data is left untouched.
; Returns #False, writing nothing, if *Cipher isn't set up.
Procedure.i BakaShrot_Cipher_EncryptTo(*Cipher.BakaShrot_Cipher, *Data, Size.i, *Sealed)
Protected Nonce.BakaShrot_CipherNonce
If Not *Cipher\IsReady Or Not *Sealed Or Size < 0 Or (Size > 0 And Not *Data) Or *Cipher\SendSequence >= #BakaShrot_Cipher_MaxSequence
ProcedureReturn #False
EndIf
; libsodium wants a valid pointer even for no data.
If Size = 0
*Data = *Sealed
EndIf
PokeQ(*Sealed, *Cipher\SendSequence)
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\SendDirection, *Cipher\SendSequence)
crypto_aead_xchacha20poly1305_ietf_encrypt(*Sealed + #BakaShrot_Cipher_SequenceSize, 0, *Data, Size,
*Sealed, #BakaShrot_Cipher_SequenceSize, 0, @Nonce, @*Cipher\SendKey[0])
*Cipher\SendSequence + 1
ProcedureReturn #True
EndProcedure
; Same, into a freshly allocated buffer of Size + #BakaShrot_Cipher_Overhead
; bytes, its size in *OutSize\i.
; Returns 0 if *Cipher isn't set up, or out of memory. The caller owns the
; returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Encrypt(*Cipher.BakaShrot_Cipher, *Data, Size.i, *OutSize.Integer)
Protected *Sealed
If Not *Cipher\IsReady Or Size < 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_Cipher_Overhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Data, Size, *Sealed)
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_Cipher_Overhead
ProcedureReturn *Sealed
EndProcedure
; Checks and decrypts *Sealed (Size bytes, as BakaShrot_Cipher_Encrypt()
; made it on the other end) into a freshly allocated buffer, the data's size
; in *OutSize\i (0 or more, the buffer is at least 1 byte).
; Returns 0 if it isn't the next buffer expected (replayed, reordered, one
; missing), was tampered with, made with another key, sent by this end, or
; is too short; also if *Cipher isn't set up, or out of memory. Nothing
; changes then, but the connection can't be trusted anymore: abort it.
; The caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Decrypt(*Cipher.BakaShrot_Cipher, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i, Nonce.BakaShrot_CipherNonce, Genuine.i
If Not *Cipher\IsReady Or Not *Sealed Or Size < #BakaShrot_Cipher_Overhead
ProcedureReturn 0
EndIf
; Only the next one: a replayed, reordered or missing buffer stops here.
If PeekQ(*Sealed) <> *Cipher\ReceiveSequence
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_Cipher_Overhead
If DataSize > 0
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
Else
*Data = AllocateMemory(1)
EndIf
If Not *Data
ProcedureReturn 0
EndIf
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\ReceiveDirection, *Cipher\ReceiveSequence)
Genuine = Bool(crypto_aead_xchacha20poly1305_ietf_decrypt(*Data, 0, 0, *Sealed + #BakaShrot_Cipher_SequenceSize, Size - #BakaShrot_Cipher_SequenceSize,
*Sealed, #BakaShrot_Cipher_SequenceSize, @Nonce, @*Cipher\ReceiveKey[0]) = 0)
If Not Genuine
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*Cipher\ReceiveSequence + 1
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
+91 -11
View File
@@ -1,17 +1,18 @@
; ============================================================================
; BakaShrot Cryptography
;
; Authenticates packets using Ed25519 signatures (via libsodium - this does
; NOT reimplement any cryptographic primitive).
; Ed25519 signatures via libsodium (this does NOT reimplement any
; cryptographic primitive).
;
; EncodeData signs a buffer with the sending node's own private key.
; DecodeData checks that signature against the claimed sender's public key.
; (Misnamed: they sign and verify, nothing is encoded or decoded.)
;
; This buys integrity + authenticity, NOT confidentiality: anyone who can see
; the packet can still read it, but they cannot forge one or tamper with one
; without the signature check failing. That matches BakaShrot's
; replication/broadcast model, where a message is meant to be read by every
; peer in the group - encrypting it for a single recipient would defeat that.
; The signatures prove each end's identity in the handshake. The sealed
; boxes, key exchange and XChaCha20-Poly1305 below encrypt the connections:
; Session.pbi and Cipher.pbi use them, nothing else should.
; What's done, what isn't, and the plan to abstract it:
; Design/Cryptography.md.
;
; Key material:
; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes.
@@ -24,8 +25,9 @@
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
;
; Setup required to build/run this:
; - Windows: the official libsodium release's "libsodium.lib" (import
; library) and "libsodium.dll" alongside the executable.
; - Windows: the official libsodium MSVC release's dynamic build, extracted
; to Libs/libsodium/<x64|x86>/ by Build.ps1, and "libsodium.dll"
; alongside the executable.
; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora)
; installed, so "-lsodium" resolves at link time and
; libsodium.so.* is available at runtime.
@@ -38,9 +40,27 @@
#BakaShrot_Ed25519_PrivateKeySize = 64
#BakaShrot_Ed25519_SignatureSize = 64
; XChaCha20-Poly1305 (IETF), libsodium's crypto_aead_xchacha20poly1305_ietf_*:
; encryption and authentication of a buffer with a shared key, used by
; Commons/Cryptography/Cipher.pbi.
#BakaShrot_XChaCha20Poly1305_KeySize = 32
#BakaShrot_XChaCha20Poly1305_NonceSize = 24
#BakaShrot_XChaCha20Poly1305_TagSize = 16
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ImportC "libsodium.lib"
; X25519 (crypto_box_seal, crypto_kx_*): sealed Hellos and the key exchange,
; used by Commons/Cryptography/Session.pbi.
#BakaShrot_X25519_PublicKeySize = 32
#BakaShrot_X25519_SecretKeySize = 32
#BakaShrot_SealedBoxOverhead = 48
#BakaShrot_KxSessionKeySize = 32
; Windows: the dynamic build's import library, libsodium.dll must be next to
; the program. Both are extracted from Libs/libsodium-*-msvc.zip by Build.ps1.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows And #PB_Compiler_Processor = #PB_Processor_x64
ImportC "../../Libs/libsodium/x64/libsodium.lib"
CompilerElseIf #PB_Compiler_OS = #PB_OS_Windows
ImportC "../../Libs/libsodium/x86/libsodium.lib"
CompilerElse
ImportC "-lsodium"
CompilerEndIf
@@ -63,6 +83,58 @@ CompilerEndIf
; non-zero otherwise (forged, corrupted, or signed different data).
crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey)
; Encrypts *Message (MessageLength bytes) into *Ciphertext (MessageLength +
; #BakaShrot_XChaCha20Poly1305_TagSize bytes, the tag at the end), with
; *Key (32 bytes) and *Nonce (24 bytes, never twice with the same key).
; *AdditionalData (AdLength bytes, may be 0) is authenticated, not
; encrypted. *Nsec is always 0. Always returns 0.
crypto_aead_xchacha20poly1305_ietf_encrypt.l(*Ciphertext, *CiphertextLength, *Message, MessageLength.q, *AdditionalData, AdLength.q, *Nsec, *Nonce, *Key)
; Checks and decrypts *Ciphertext (CiphertextLength bytes, tag included)
; into *Message (CiphertextLength - TagSize bytes). Returns 0 if it's
; genuine, -1 if it was tampered with, or made with another key, nonce or
; additional data: *Message must not be used then.
crypto_aead_xchacha20poly1305_ietf_decrypt.l(*Message, *MessageLength, *Nsec, *Ciphertext, CiphertextLength.q, *AdditionalData, AdLength.q, *Nonce, *Key)
; Fills *Key (32 bytes) with a random XChaCha20-Poly1305 key.
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
; Zeroes Length bytes at *Memory, in a way the compiler can't optimize out:
; for wiping keys.
sodium_memzero(*Memory, Length.i)
; Copies the public key embedded in *PrivateKey (64 bytes) into *PublicKey
; (32 bytes). Always returns 0.
crypto_sign_ed25519_sk_to_pk.l(*PublicKey, *PrivateKey)
; The X25519 key (32 bytes) matching an Ed25519 public key (32 bytes) or
; private key (64 bytes), so one identity key both signs and receives
; sealed boxes. The public one returns -1 if it isn't a valid key.
crypto_sign_ed25519_pk_to_curve25519.l(*X25519PublicKey, *Ed25519PublicKey)
crypto_sign_ed25519_sk_to_curve25519.l(*X25519SecretKey, *Ed25519PrivateKey)
; Encrypts *Message (MessageLength bytes) for the holder of *PublicKey
; (X25519) into *Ciphertext (MessageLength + 48 bytes), with a throwaway
; key pair: only *PublicKey's holder can open it, and it doesn't tell who
; sealed it. Returns 0, -1 on failure.
crypto_box_seal.l(*Ciphertext, *Message, MessageLength.q, *PublicKey)
; Opens *Ciphertext (CiphertextLength bytes) sealed for *PublicKey into
; *Message (CiphertextLength - 48 bytes). Returns 0, or -1 if it wasn't
; sealed for this key or was tampered with.
crypto_box_seal_open.l(*Message, *Ciphertext, CiphertextLength.q, *PublicKey, *SecretKey)
; Fills *PublicKey and *SecretKey (32 bytes each) with a fresh X25519 key
; pair, for one key exchange. Returns 0.
crypto_kx_keypair.l(*PublicKey, *SecretKey)
; Both ends of a key exchange get the same two 32-byte keys from their own
; key pair and the other end's public key: *Rx decrypts what this end
; receives, *Tx encrypts what it sends (the client's Tx is the server's
; Rx). Return -1 if the other end's public key isn't acceptable.
crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey)
crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey)
EndImport
@@ -82,6 +154,14 @@ Procedure GenerateKeyPair(*PublicKey, *PrivateKey)
EndProcedure
; Fills *PublicKey (#BakaShrot_Ed25519_PublicKeySize bytes) with the public
; key matching *PrivateKey (#BakaShrot_Ed25519_PrivateKeySize bytes), so a
; node only needs its private key in its config.
Procedure GetPublicKeyFromPrivateKey(*PrivateKey, *PublicKey)
crypto_sign_ed25519_sk_to_pk(*PublicKey, *PrivateKey)
EndProcedure
; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private
; key, #BakaShrot_Ed25519_PrivateKeySize bytes).
; Writes the signature to *Signature, which must point to
+186
View File
@@ -0,0 +1,186 @@
; ============================================================================
; BakaShrot Session
;
; The handshake's cryptography, so the connections only call these
; (the handshake itself is in Commons/Networking/Connections.pbi):
;
; - The Hello is sealed for the server's identity key: crypto_box_seal,
; for the X25519 key matching the server's Ed25519 one. Only that
; server can read it, and someone watching doesn't learn who connects.
; BakaShrot_Session_SealHello() / _OpenHello().
; - Each end makes a key pair for this one connection (crypto_kx). The
; client's public half travels in the sealed Hello, the server's in the
; ChallengeRequest; both ends sign them with their identity keys
; (Connections.pbi), so nobody in the middle can swap them.
; BakaShrot_Session_NewKeyPair().
; - From its own pair and the other end's public half, each end gets a
; key per direction and sets its BakaShrot_Cipher (Cipher.pbi) up with
; them: every packet after the ChallengeRequest is encrypted.
; BakaShrot_Session_StartClient() / _StartServer().
;
; The key pair's secret and the derived keys are wiped once the cipher has
; them: a recorded connection can't be decrypted later, even with the
; identity keys (forward secrecy).
;
; libsodium does all of it (Libsodium.pbi), InitCryptography() must have
; been called.
; ============================================================================
XIncludeFile "Cipher.pbi"
#BakaShrot_Session_PublicKeySize = #BakaShrot_X25519_PublicKeySize
Structure BakaShrot_SessionKey
Bytes.a[32]
EndStructure
; One end's key pair for one connection.
Structure BakaShrot_SessionKeyPair
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
; A server's keys to open the Hellos sealed for it, from its Ed25519
; private key. Read-only once loaded, every client thread may use them.
Structure BakaShrot_HelloKeys
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
Structure BakaShrot_SessionDirections
Rx.a[#BakaShrot_KxSessionKeySize]
Tx.a[#BakaShrot_KxSessionKeySize]
EndStructure
; Fills *Keys from *PrivateKey (Ed25519, #BakaShrot_Ed25519_PrivateKeySize
; bytes), for a server to open the Hellos sealed for its public key.
; Returns #False if it isn't a usable key.
Procedure.i BakaShrot_Session_LoadHelloKeys(*Keys.BakaShrot_HelloKeys, *PrivateKey)
Protected Ed25519PublicKey.BakaShrot_SessionKey, IsValid.i
crypto_sign_ed25519_sk_to_pk(@Ed25519PublicKey, *PrivateKey)
IsValid = Bool(crypto_sign_ed25519_pk_to_curve25519(@*Keys\PublicKey[0], @Ed25519PublicKey) = 0)
If IsValid
IsValid = Bool(crypto_sign_ed25519_sk_to_curve25519(@*Keys\SecretKey[0], *PrivateKey) = 0)
EndIf
If Not IsValid
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndIf
ProcedureReturn IsValid
EndProcedure
; Wipes *Keys.
Procedure BakaShrot_Session_ClearHelloKeys(*Keys.BakaShrot_HelloKeys)
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndProcedure
; Seals *Data (Size bytes, at least 1) for the server whose Ed25519 public
; key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize bytes), into a
; freshly allocated buffer of Size + #BakaShrot_SealedBoxOverhead bytes,
; its size in *OutSize\i.
; Returns 0 if *ServerPublicKey isn't a valid key, or out of memory. The
; caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Session_SealHello(*ServerPublicKey, *Data, Size.i, *OutSize.Integer)
Protected BoxPublicKey.BakaShrot_SessionKey, *Sealed
If Not *ServerPublicKey Or Not *Data Or Size < 1
ProcedureReturn 0
EndIf
If crypto_sign_ed25519_pk_to_curve25519(@BoxPublicKey, *ServerPublicKey) <> 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_SealedBoxOverhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If crypto_box_seal(*Sealed, *Data, Size, @BoxPublicKey) <> 0
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_SealedBoxOverhead
ProcedureReturn *Sealed
EndProcedure
; Opens *Sealed (Size bytes), sealed by BakaShrot_Session_SealHello() for
; *Keys' server, into a freshly allocated buffer, its size in *OutSize\i.
; Returns 0 if it wasn't sealed for this server, was tampered with, is too
; short, or out of memory. The caller owns the returned buffer - free it
; with FreeMemory.
Procedure.i BakaShrot_Session_OpenHello(*Keys.BakaShrot_HelloKeys, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i
If Not *Sealed Or Size <= #BakaShrot_SealedBoxOverhead
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_SealedBoxOverhead
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
If Not *Data
ProcedureReturn 0
EndIf
If crypto_box_seal_open(*Data, *Sealed, Size, @*Keys\PublicKey[0], @*Keys\SecretKey[0]) <> 0
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
; Fills *KeyPair with a fresh key pair, for one connection. Its PublicKey
; goes to the other end.
Procedure BakaShrot_Session_NewKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
crypto_kx_keypair(@*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0])
EndProcedure
; Wipes *KeyPair.
Procedure BakaShrot_Session_ClearKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
sodium_memzero(*KeyPair, SizeOf(BakaShrot_SessionKeyPair))
EndProcedure
; Sets *Cipher up for the client's end of the connection, from the client's
; *KeyPair and the server's public half (*ServerSessionKey,
; #BakaShrot_Session_PublicKeySize bytes). *KeyPair is wiped either way.
; Returns #False if the server's half isn't acceptable: abort then.
Procedure.i BakaShrot_Session_StartClient(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ServerSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_client_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ServerSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure
; Same for the server's end, from the server's *KeyPair and the client's
; public half (*ClientSessionKey).
Procedure.i BakaShrot_Session_StartServer(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ClientSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_server_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ClientSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure