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

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+255
View File
@@ -0,0 +1,255 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Cipher.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,345 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Libsodium.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Cryptography
;
; 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.)
;
; 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.
; - Private key: #BakaShrot_Ed25519_PrivateKeySize (64) raw bytes.
; (libsodium's Ed25519 secret key already embeds the seed and the public
; key, which is why it is twice the size of the public key.)
; A node's private key lives in BakaShrot_CoreConfig\PrivateKey (Config.pbi);
; the public key it hands out to peers lives in each
; BakaShrot_PeerConfig\PublicKey. Both are stored as Base64 text in the ini
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
;
; Setup required to build/run this:
; - 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.
; libsodium itself is the same standard, audited library on both platforms,
; so signatures made on one are verifiable on the other without change.
; ============================================================================
#BakaShrot_Ed25519_PublicKeySize = 32
#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
; 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
; Must be called once (any number of extra calls are harmless) before any
; other function below is used. Returns 0 on success, 1 if it was already
; initialized, -1 if libsodium failed to self-check (e.g. no RNG available).
sodium_init.l()
; Fills *PublicKey (32 bytes) and *PrivateKey (64 bytes) with a fresh,
; cryptographically random Ed25519 keypair.
crypto_sign_keypair.l(*PublicKey, *PrivateKey)
; Writes a #BakaShrot_Ed25519_SignatureSize-byte signature of *Message
; (MessageLength bytes) to *Signature, made with *PrivateKey.
crypto_sign_detached.l(*Signature, *SignatureLength, *Message, MessageLength.q, *PrivateKey)
; Returns 0 if *Signature is a valid signature of *Message (MessageLength
; bytes) made by the holder of the private key matching *PublicKey;
; 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)
; SHA-256, a piece at a time: _init() a state (crypto_hash_sha256_statebytes()
; bytes), _update() it with each piece, _final() writes the 32-byte hash.
; For the attachments' checksums, see BakaShrot_Sha256_* below.
crypto_hash_sha256_statebytes.i()
crypto_hash_sha256_init.l(*State)
crypto_hash_sha256_update.l(*State, *Data, DataLength.q)
crypto_hash_sha256_final.l(*State, *Hash)
; SHA-256 of DataLength bytes at *Data in one go, the 32-byte hash into
; *Hash. Certificates' fingerprints and key ids (X509.pbi).
crypto_hash_sha256.l(*Hash, *Data, DataLength.q)
; Fills *Buffer with Size bytes from the OS's secure generator.
; Certificates' serial numbers.
randombytes_buf(*Buffer, Size.i)
; The Ed25519 key pair of a 32-byte seed, which is what PKCS#8 private
; key files hold, and the seed of a 64-byte private key. Both return 0.
crypto_sign_seed_keypair.l(*PublicKey, *PrivateKey, *Seed)
crypto_sign_ed25519_sk_to_seed.l(*Seed, *PrivateKey)
; Base64 (Variant #BakaShrot_Base64_Original for PEM), constant-time.
; _encoded_len() is the size *Base64 needs, terminator included.
; bin2base64 writes a terminated ASCII string, returns *Base64.
; base642bin skips the characters of the ASCII string *Ignore (" \r\n"),
; and returns -1 if anything else isn't Base64 or *Binary is too small
; (*End = 0: all of it must decode). The size it wrote goes in *BinaryLength.
sodium_base64_encoded_len.i(BinaryLength.i, Variant.l)
sodium_bin2base64.i(*Base64, MaxLength.i, *Binary, BinaryLength.i, Variant.l)
sodium_base642bin.l(*Binary, MaxLength.i, *Base64, Base64Length.i, *Ignore, *BinaryLength, *End, Variant.l)
; Hex, lowercase, constant-time; same conventions as Base64 above.
sodium_bin2hex.i(*Hex, MaxLength.i, *Binary, BinaryLength.i)
sodium_hex2bin.l(*Binary, MaxLength.i, *Hex, HexLength.i, *Ignore, *BinaryLength, *End)
EndImport
; sodium_base64_VARIANT_ORIGINAL: the standard alphabet, with padding.
#BakaShrot_Base64_Original = 1
; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData.
; Returns #False if libsodium could not initialize - treat that as fatal,
; there is no safe fallback to running without it.
Procedure.i InitCryptography()
ProcedureReturn Bool(sodium_init() >= 0)
EndProcedure
; Generates a new Ed25519 keypair for provisioning a node.
; *PublicKey must point to #BakaShrot_Ed25519_PublicKeySize bytes,
; *PrivateKey to #BakaShrot_Ed25519_PrivateKeySize bytes.
Procedure GenerateKeyPair(*PublicKey, *PrivateKey)
crypto_sign_keypair(*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
; #BakaShrot_Ed25519_SignatureSize bytes. *Data itself is left untouched.
Procedure.i EncodeData(*Data, DataLength.i, *PrivateKey, *Signature)
Protected SignatureLength.q
ProcedureReturn Bool(crypto_sign_detached(*Signature, @SignatureLength, *Data, DataLength, *PrivateKey) = 0)
EndProcedure
; Verifies that *Signature (#BakaShrot_Ed25519_SignatureSize bytes) is a
; valid signature of *Data (DataLength bytes), made by the holder of the
; private key matching *PublicKey (the claimed sender's public key, from
; BakaShrot_PeerConfig\PublicKey).
; Returns #True only if the signature checks out. On #False, reject the
; packet outright - do not process it, do not fall back to trusting it.
Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature)
ProcedureReturn Bool(crypto_sign_verify_detached(*Signature, *Data, DataLength, *PublicKey) = 0)
EndProcedure
; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add
; each piece, then Finish writes the 32-byte hash.
#BakaShrot_Sha256_HashSize = 32
Structure BakaShrot_Sha256
; crypto_hash_sha256_state is 104 bytes, checked by Start.
State.a[128]
EndStructure
; Returns #False if libsodium's state doesn't fit (a libsodium change).
Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256)
If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256)
ProcedureReturn #False
EndIf
ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0)
EndProcedure
Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i)
If Size > 0
crypto_hash_sha256_update(*Hash, *Data, Size)
EndIf
EndProcedure
Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out)
crypto_hash_sha256_final(*Hash, *Out)
EndProcedure
; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in
; the ini file (PrivateKey / PublicKey fields in Config.pbi).
Procedure.s EncodeKeyToString(*Key, KeySize.i)
ProcedureReturn Base64Encoder(*Key, KeySize)
EndProcedure
; Decodes KeyString back into KeySize raw bytes at *Key.
; Returns #False (and leaves *Key untouched) if KeyString is not valid
; Base64 or does not decode to exactly KeySize bytes - a malformed or
; truncated key in the config file must never be silently accepted as one
; that's merely different.
Procedure.i DecodeKeyFromString(KeyString.s, *Key, KeySize.i)
; PureBasic's own docs warn the output buffer must have some slack over
; the exact decoded size or the decoder can overflow it - at least 25%
; extra and never under 64 bytes, hence the margin below.
Protected *Buffer, BufferSize.i, DecodedSize.i
BufferSize = (KeySize * 5) / 4 + 64
*Buffer = AllocateMemory(BufferSize)
DecodedSize = Base64Decoder(KeyString, *Buffer, BufferSize)
If DecodedSize = KeySize
CopyMemory(*Buffer, *Key, KeySize)
EndIf
FreeMemory(*Buffer)
ProcedureReturn Bool(DecodedSize = KeySize)
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
If Not InitCryptography()
Debug "Failed to initialize libsodium."
Else
Define *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *Signature = AllocateMemory(#BakaShrot_Ed25519_SignatureSize)
Define Message.s = ~"{\"messageData\": {\"MsgType\": \"hello\"}}"
Define MessageLength = StringByteLength(Message, #PB_Ascii)
Define *MessageBytes = AllocateMemory(MessageLength)
PokeS(*MessageBytes, Message, -1, #PB_Ascii)
GenerateKeyPair(*PublicKey, *PrivateKey)
Debug "PublicKey: " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize)
Debug "PrivateKey: " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize)
If EncodeData(*MessageBytes, MessageLength, *PrivateKey, *Signature)
Debug "Signed ok. Signature: " + EncodeKeyToString(*Signature, #BakaShrot_Ed25519_SignatureSize)
If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature)
Debug "Verified ok, as expected."
Else
Debug "FAILED to verify a genuine signature - something is broken."
EndIf
; Tamper with one byte and make sure verification then rejects it.
PokeB(*MessageBytes, PeekB(*MessageBytes) ! 1)
If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature)
Debug "FAILED: tampered data was accepted as genuine."
Else
Debug "Tampered data correctly rejected."
EndIf
Else
Debug "Failed to sign data."
EndIf
FreeMemory(*PublicKey)
FreeMemory(*PrivateKey)
FreeMemory(*Signature)
FreeMemory(*MessageBytes)
EndIf
CompilerEndIf
+203
View File
@@ -0,0 +1,203 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Session.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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
File diff suppressed because it is too large Load Diff