From e044fcf3599b48ac6e646326d21313e26cb42f4f Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Sat, 14 Nov 2026 12:47:40 +0100 Subject: [PATCH 1/6] 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 Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb --- .github/workflows/source.yml | 30 + .gitignore | 11 +- .gitmodules | 2 +- CLAUDE.md | 144 +- Build.ps1 => OldSource/Build.ps1 | 0 OldSource/CLAUDE.md | 121 ++ .../Client}/BakaShrot_Client.pbi | 0 .../Client}/BakaShrot_Client.pbi.cfg | 0 .../Client}/BakaShrot_Client_Prototypes.pbi | 0 .../Client}/BakaShrot_ErrorCodes.pbi | 0 {Client => OldSource/Client}/notes.txt | 0 OldSource/Commons/Console.pbi | 0 .../Commons}/Cryptography/Cipher.pbi | 0 OldSource/Commons/Cryptography/Der.pbi | 1084 +++++++++++ .../Commons}/Cryptography/Libsodium.pbi | 30 + .../Commons}/Cryptography/Session.pbi | 0 OldSource/Commons/Cryptography/X509.pbi | 1712 +++++++++++++++++ .../Commons}/Networking/Connections.pbi | 0 .../Commons}/Networking/Names.pbi | 0 .../Commons}/Networking/Outbound.pbi | 0 .../Commons}/Networking/Packets.pbi | 0 .../Packets/AttachmentChunkPacket.pbi | 0 .../Networking/Packets/AuthAcceptedPacket.pbi | 0 .../Packets/ChallengeRequestPacket.pbi | 0 .../Packets/ChallengeResponsePacket.pbi | 0 .../Networking/Packets/ChunkStoredPacket.pbi | 0 .../Packets/GetAttachmentPacket.pbi | 0 .../Packets/GetLatestMessagePacket.pbi | 0 .../Networking/Packets/GetMessagesPacket.pbi | 0 .../Networking/Packets/HelloPacket.pbi | 0 .../Packets/LatestMessagePacket.pbi | 0 .../Networking/Packets/ListNamesPacket.pbi | 0 .../Packets/MessagePushedPacket.pbi | 0 .../Networking/Packets/MessagesPacket.pbi | 0 .../Packets/MissingAttachmentsPacket.pbi | 0 .../MissingAttachmentsRequestPacket.pbi | 0 .../Networking/Packets/NameResolvedPacket.pbi | 0 .../Networking/Packets/NamesListPacket.pbi | 0 .../Networking/Packets/PushMessagePacket.pbi | 0 .../Networking/Packets/QueryRequestPacket.pbi | 0 .../Networking/Packets/QueryResultPacket.pbi | 0 .../ReplicateAttachmentChunkPacket.pbi | 0 .../Packets/ReplicateMessagesPacket.pbi | 0 .../Packets/RequestRefusedPacket.pbi | 0 .../Networking/Packets/ResolveNamePacket.pbi | 0 .../Networking/Packets/SyncStatePacket.pbi | 0 .../Packets/SyncStateRequestPacket.pbi | 0 .../Networking/Packets/UploadChunkPacket.pbi | 0 .../Networking/Packets/UploadStartPacket.pbi | 0 .../Packets/UploadStartedPacket.pbi | 0 .../Commons}/Networking/SocketWait.pbi | 0 .../Commons}/Threading/Signal.pbi | 0 {Design => OldSource/Design}/Attachments.md | 0 OldSource/Design/Certificates.md | 154 ++ {Design => OldSource/Design}/Cryptography.md | 5 + {Design => OldSource/Design}/Packets.md | 0 {Design => OldSource/Design}/Release.md | 0 .../Design}/ReplicationIssues.md | 0 .../Design}/StorageConcurrency.md | 0 {Design => OldSource/Design}/Suggestions.md | 0 {Docker => OldSource/Docker}/README.md | 0 .../Docker}/Server/Dockerfile | 0 .../Docker}/Server/Dockerfile.dockerignore | 0 .../Docker}/Server/docker-compose.yml | 0 .../Docker}/Server/server.ini | 0 {Examples => OldSource/Examples}/README.md | 0 .../Examples}/SingleServer/README.md | 0 .../Examples}/SingleServer/Run-Client.ps1 | 0 .../Examples}/SingleServer/Start-Server.ps1 | 0 .../Examples}/SingleServer/client.ini | 0 .../SingleServer/messages/hello.json | 0 .../Examples}/SingleServer/messages/query.sql | 0 .../SingleServer/messages/reading.json | 0 .../SingleServer/messages/report.json | 0 .../SingleServer/messages/report.txt | 0 .../Examples}/SingleServer/server.ini | 0 .../Includes}/PB-MessagePack | 0 .../Interactors}/Python/README.md | 0 .../Interactors}/Python/bakashrot.py | 0 .../Interactors}/Python/check_bakashrot.py | 0 .../Interactors}/Python/example.py | 0 .../Interactors}/Python/make_wheel.py | 4 +- .../Interactors}/Python/notes.txt | 0 .../Index of -libsodium-releases-.url | 0 {Libs => OldSource/Libs}/libsodium/LICENSE | 0 {Libs => OldSource/Libs}/redist/README.md | 0 .../Libs}/redist/x64/vcruntime140.dll | Bin Notes.md => OldSource/Notes.md | 34 + Release.ps1 => OldSource/Release.ps1 | 2 +- .../Server}/BakaShrot_Server.pb | 12 + .../Server}/BakaShrot_Server.pb.cfg | 0 .../Server}/Config/Config.pbi | 0 .../Server}/Config/Config.pbi.cfg | 0 .../Server}/Config/schema.ini | 0 .../Server}/Config/schema_out.ini | 0 .../Server}/Networking/Networking.pbi | 0 .../Server}/Networking/Networking.pbi.cfg | 0 .../Server}/Networking/Peers.pbi | 0 {Server => OldSource/Server}/Root.pbi | 0 .../Server}/Storage/Attachments.pbi | 0 .../Server}/Storage/Names.pbi | 0 .../Server}/Storage/Retention.pbi | 0 .../Server}/Storage/Storage.pbi | 0 .../Server}/Storage/Writer.pbi | 0 .../Server}/Storage/db_schema_v0.dbml | 0 .../Server}/Storage/db_schema_v1.dbml | 0 .../Server}/Storage/db_schema_v2.dbml | 0 .../Server}/Storage/db_schema_v3.dbml | 0 .../Server}/Storage/db_schema_v4.dbml | 0 .../Server}/Storage/db_schema_v5.dbml | 0 .../Server}/Storage/db_schema_v6.dbml | 0 .../Server}/Storage/db_schema_v7.dbml | 0 .../Server}/Storage/db_schema_v8.dbml | 0 .../Tests}/AttachmentEdgeClient.pb | 0 .../Tests}/AttachmentEdges-Test.ps1 | 0 .../Tests}/Attachments-Test.ps1 | 0 .../Tests}/Bench/Bench-Replication.ps1 | 0 .../Tests}/Bench/BenchClient.pb | 0 {Tests => OldSource/Tests}/Bench/BenchSeed.pb | 0 .../Tests}/Bench/BenchServer.pb | 0 .../Tests}/Bench/Compare-Runs.ps1 | 0 .../Tests}/Bench/Results-2026-11-07.md | 0 {Tests => OldSource/Tests}/Bench/queries.txt | 0 .../Tests}/Bench/queries_load.txt | 0 .../Tests}/BigMessages-Test.ps1 | 0 {Tests => OldSource/Tests}/CipherTest.pb | 0 .../Tests}/GetMessages-Test.ps1 | 0 {Tests => OldSource/Tests}/HandshakeTest.pb | 0 {Tests => OldSource/Tests}/Names-Test.ps1 | 0 {Tests => OldSource/Tests}/Python-Test.ps1 | 0 {Tests => OldSource/Tests}/Restart-Test.ps1 | 0 {Tests => OldSource/Tests}/Retention-Test.ps1 | 0 OldSource/Tests/X509-Test.ps1 | 102 + OldSource/Tests/X509Test.pb | 745 +++++++ {Tests => OldSource/Tests}/restart_pusher.py | 0 {Tests => OldSource/Tests}/wire_check.py | 0 .../BakaShrotGenerateKeyPairs.pb | 0 .../BakaShrotGetAttachment.pb | 0 .../BakaShrotGetLatestMessage.pb | 0 .../BakaShrotGetMessages.pb | 0 .../Tools}/BakaShrotList/BakaShrotList.pb | 0 .../Tools}/BakaShrotList/BakaShrotList.pb.cfg | 0 .../BakaShrotPushMessage.pb | 0 .../Tools}/BakaShrotQuery/BakaShrotQuery.pb | 0 .../BakaShrotResolveIds.pb | 0 .../BakaShrotResolveIds.pb.cfg | 0 .../Tools}/Common/ToolClient.pbi | 0 .../Tools}/Common/ToolConsole.pbi | 0 Source/.cargo/config.toml | 11 + Source/.gitattributes | 3 + Source/Cargo.lock | 1423 ++++++++++++++ Source/Cargo.toml | 32 + Source/README.md | 57 + Source/bindings/c/bakashrot.h | 355 ++++ .../purebasic/BakaShrot_Client_Prototypes.pbi | 322 ++++ .../purebasic/BakaShrot_ErrorCodes.pbi | 144 ++ Source/bindings/python/bakashrot.py | 577 ++++++ Source/bindings/python/check_bakashrot.py | 247 +++ Source/check.ps1 | 29 + Source/crates/bakashrot-capi/Cargo.toml | 30 + Source/crates/bakashrot-capi/cbindgen.toml | 13 + Source/crates/bakashrot-capi/src/lib.rs | 928 +++++++++ Source/crates/bakashrot-capi/src/text.rs | 95 + .../crates/bakashrot-capi/tests/common/mod.rs | 95 + Source/crates/bakashrot-capi/tests/exports.rs | 341 ++++ Source/crates/bakashrot-capi/tests/header.rs | 20 + Source/crates/bakashrot-capi/tests/python.rs | 66 + Source/crates/bakashrot-client/Cargo.toml | 21 + Source/crates/bakashrot-client/src/lib.rs | 543 ++++++ Source/crates/bakashrot-config/Cargo.toml | 23 + Source/crates/bakashrot-config/example.toml | 67 + Source/crates/bakashrot-config/src/lib.rs | 317 +++ Source/crates/bakashrot-config/src/roles.rs | 143 ++ Source/crates/bakashrot-config/src/values.rs | 253 +++ .../crates/bakashrot-config/tests/config.rs | 372 ++++ Source/crates/bakashrot-pki/Cargo.toml | 25 + Source/crates/bakashrot-pki/src/ca.rs | 238 +++ Source/crates/bakashrot-pki/src/identity.rs | 147 ++ Source/crates/bakashrot-pki/src/lib.rs | 87 + Source/crates/bakashrot-pki/src/revocation.rs | 91 + Source/crates/bakashrot-pki/src/tls.rs | 254 +++ Source/crates/bakashrot-pki/tests/ca.rs | 235 +++ Source/crates/bakashrot-pki/tests/tls.rs | 388 ++++ Source/crates/bakashrot-proto/Cargo.toml | 28 + Source/crates/bakashrot-proto/src/error.rs | 181 ++ Source/crates/bakashrot-proto/src/frame.rs | 252 +++ Source/crates/bakashrot-proto/src/lib.rs | 23 + Source/crates/bakashrot-proto/src/limits.rs | 105 + Source/crates/bakashrot-proto/src/names.rs | 148 ++ .../src/packets/attachments.rs | 108 ++ .../bakashrot-proto/src/packets/messages.rs | 235 +++ .../crates/bakashrot-proto/src/packets/mod.rs | 324 ++++ .../src/packets/replication.rs | 199 ++ .../bakashrot-proto/src/packets/session.rs | 76 + .../crates/bakashrot-proto/tests/packets.rs | 563 ++++++ Source/crates/bakashrot-server/Cargo.toml | 31 + .../crates/bakashrot-server/src/connection.rs | 519 +++++ Source/crates/bakashrot-server/src/lib.rs | 277 +++ Source/crates/bakashrot-server/src/main.rs | 40 + .../crates/bakashrot-server/src/retention.rs | 69 + Source/crates/bakashrot-server/src/writer.rs | 161 ++ .../bakashrot-server/tests/end_to_end.rs | 1052 ++++++++++ Source/crates/bakashrot-storage/Cargo.toml | 28 + Source/crates/bakashrot-storage/src/batch.rs | 394 ++++ .../crates/bakashrot-storage/src/database.rs | 194 ++ Source/crates/bakashrot-storage/src/lib.rs | 265 +++ Source/crates/bakashrot-storage/src/query.rs | 95 + Source/crates/bakashrot-storage/src/reader.rs | 225 +++ .../bakashrot-storage/src/schema_v9.sql | 146 ++ .../crates/bakashrot-storage/tests/storage.rs | 848 ++++++++ Source/crates/bakashrot-tools/Cargo.toml | 34 + .../bakashrot-tools/src/bin/bakashrot-cert.rs | 241 +++ .../bakashrot-tools/src/bin/bakashrot.rs | 388 ++++ .../crates/bakashrot-tools/tests/bakashrot.rs | 556 ++++++ Source/crates/bakashrot-tools/tests/cert.rs | 149 ++ Source/docs/certificates.md | 135 ++ Source/docs/client.md | 186 ++ Source/docs/config.md | 105 + Source/docs/oid.md | 77 + Source/docs/protocol.md | 183 ++ Source/docs/server.md | 218 +++ Source/docs/storage.md | 285 +++ Source/rust-toolchain.toml | 6 + readme.md | 20 +- revamp.md | 619 ++++++ 225 files changed, 21849 insertions(+), 123 deletions(-) create mode 100644 .github/workflows/source.yml rename Build.ps1 => OldSource/Build.ps1 (100%) create mode 100644 OldSource/CLAUDE.md rename {Client => OldSource/Client}/BakaShrot_Client.pbi (100%) rename {Client => OldSource/Client}/BakaShrot_Client.pbi.cfg (100%) rename {Client => OldSource/Client}/BakaShrot_Client_Prototypes.pbi (100%) rename {Client => OldSource/Client}/BakaShrot_ErrorCodes.pbi (100%) rename {Client => OldSource/Client}/notes.txt (100%) create mode 100644 OldSource/Commons/Console.pbi rename {Commons => OldSource/Commons}/Cryptography/Cipher.pbi (100%) create mode 100644 OldSource/Commons/Cryptography/Der.pbi rename {Commons => OldSource/Commons}/Cryptography/Libsodium.pbi (89%) rename {Commons => OldSource/Commons}/Cryptography/Session.pbi (100%) create mode 100644 OldSource/Commons/Cryptography/X509.pbi rename {Commons => OldSource/Commons}/Networking/Connections.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Names.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Outbound.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/AttachmentChunkPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/AuthAcceptedPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ChallengeRequestPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ChallengeResponsePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ChunkStoredPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/GetAttachmentPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/GetLatestMessagePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/GetMessagesPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/HelloPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/LatestMessagePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ListNamesPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/MessagePushedPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/MessagesPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/MissingAttachmentsPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/MissingAttachmentsRequestPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/NameResolvedPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/NamesListPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/PushMessagePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/QueryRequestPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/QueryResultPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ReplicateAttachmentChunkPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ReplicateMessagesPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/RequestRefusedPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/ResolveNamePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/SyncStatePacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/SyncStateRequestPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/UploadChunkPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/UploadStartPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/Packets/UploadStartedPacket.pbi (100%) rename {Commons => OldSource/Commons}/Networking/SocketWait.pbi (100%) rename {Commons => OldSource/Commons}/Threading/Signal.pbi (100%) rename {Design => OldSource/Design}/Attachments.md (100%) create mode 100644 OldSource/Design/Certificates.md rename {Design => OldSource/Design}/Cryptography.md (95%) rename {Design => OldSource/Design}/Packets.md (100%) rename {Design => OldSource/Design}/Release.md (100%) rename {Design => OldSource/Design}/ReplicationIssues.md (100%) rename {Design => OldSource/Design}/StorageConcurrency.md (100%) rename {Design => OldSource/Design}/Suggestions.md (100%) rename {Docker => OldSource/Docker}/README.md (100%) rename {Docker => OldSource/Docker}/Server/Dockerfile (100%) rename {Docker => OldSource/Docker}/Server/Dockerfile.dockerignore (100%) rename {Docker => OldSource/Docker}/Server/docker-compose.yml (100%) rename {Docker => OldSource/Docker}/Server/server.ini (100%) rename {Examples => OldSource/Examples}/README.md (100%) rename {Examples => OldSource/Examples}/SingleServer/README.md (100%) rename {Examples => OldSource/Examples}/SingleServer/Run-Client.ps1 (100%) rename {Examples => OldSource/Examples}/SingleServer/Start-Server.ps1 (100%) rename {Examples => OldSource/Examples}/SingleServer/client.ini (100%) rename {Examples => OldSource/Examples}/SingleServer/messages/hello.json (100%) rename {Examples => OldSource/Examples}/SingleServer/messages/query.sql (100%) rename {Examples => OldSource/Examples}/SingleServer/messages/reading.json (100%) rename {Examples => OldSource/Examples}/SingleServer/messages/report.json (100%) rename {Examples => OldSource/Examples}/SingleServer/messages/report.txt (100%) rename {Examples => OldSource/Examples}/SingleServer/server.ini (100%) rename {Includes => OldSource/Includes}/PB-MessagePack (100%) rename {Interactors => OldSource/Interactors}/Python/README.md (100%) rename {Interactors => OldSource/Interactors}/Python/bakashrot.py (100%) rename {Interactors => OldSource/Interactors}/Python/check_bakashrot.py (100%) rename {Interactors => OldSource/Interactors}/Python/example.py (100%) rename {Interactors => OldSource/Interactors}/Python/make_wheel.py (98%) rename {Interactors => OldSource/Interactors}/Python/notes.txt (100%) rename {Libs => OldSource/Libs}/libsodium/Index of -libsodium-releases-.url (100%) rename {Libs => OldSource/Libs}/libsodium/LICENSE (100%) rename {Libs => OldSource/Libs}/redist/README.md (100%) rename {Libs => OldSource/Libs}/redist/x64/vcruntime140.dll (100%) rename Notes.md => OldSource/Notes.md (96%) rename Release.ps1 => OldSource/Release.ps1 (99%) rename {Server => OldSource/Server}/BakaShrot_Server.pb (95%) rename {Server => OldSource/Server}/BakaShrot_Server.pb.cfg (100%) rename {Server => OldSource/Server}/Config/Config.pbi (100%) rename {Server => OldSource/Server}/Config/Config.pbi.cfg (100%) rename {Server => OldSource/Server}/Config/schema.ini (100%) rename {Server => OldSource/Server}/Config/schema_out.ini (100%) rename {Server => OldSource/Server}/Networking/Networking.pbi (100%) rename {Server => OldSource/Server}/Networking/Networking.pbi.cfg (100%) rename {Server => OldSource/Server}/Networking/Peers.pbi (100%) rename {Server => OldSource/Server}/Root.pbi (100%) rename {Server => OldSource/Server}/Storage/Attachments.pbi (100%) rename {Server => OldSource/Server}/Storage/Names.pbi (100%) rename {Server => OldSource/Server}/Storage/Retention.pbi (100%) rename {Server => OldSource/Server}/Storage/Storage.pbi (100%) rename {Server => OldSource/Server}/Storage/Writer.pbi (100%) rename {Server => OldSource/Server}/Storage/db_schema_v0.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v1.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v2.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v3.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v4.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v5.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v6.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v7.dbml (100%) rename {Server => OldSource/Server}/Storage/db_schema_v8.dbml (100%) rename {Tests => OldSource/Tests}/AttachmentEdgeClient.pb (100%) rename {Tests => OldSource/Tests}/AttachmentEdges-Test.ps1 (100%) rename {Tests => OldSource/Tests}/Attachments-Test.ps1 (100%) rename {Tests => OldSource/Tests}/Bench/Bench-Replication.ps1 (100%) rename {Tests => OldSource/Tests}/Bench/BenchClient.pb (100%) rename {Tests => OldSource/Tests}/Bench/BenchSeed.pb (100%) rename {Tests => OldSource/Tests}/Bench/BenchServer.pb (100%) rename {Tests => OldSource/Tests}/Bench/Compare-Runs.ps1 (100%) rename {Tests => OldSource/Tests}/Bench/Results-2026-11-07.md (100%) rename {Tests => OldSource/Tests}/Bench/queries.txt (100%) rename {Tests => OldSource/Tests}/Bench/queries_load.txt (100%) rename {Tests => OldSource/Tests}/BigMessages-Test.ps1 (100%) rename {Tests => OldSource/Tests}/CipherTest.pb (100%) rename {Tests => OldSource/Tests}/GetMessages-Test.ps1 (100%) rename {Tests => OldSource/Tests}/HandshakeTest.pb (100%) rename {Tests => OldSource/Tests}/Names-Test.ps1 (100%) rename {Tests => OldSource/Tests}/Python-Test.ps1 (100%) rename {Tests => OldSource/Tests}/Restart-Test.ps1 (100%) rename {Tests => OldSource/Tests}/Retention-Test.ps1 (100%) create mode 100644 OldSource/Tests/X509-Test.ps1 create mode 100644 OldSource/Tests/X509Test.pb rename {Tests => OldSource/Tests}/restart_pusher.py (100%) rename {Tests => OldSource/Tests}/wire_check.py (100%) rename {Tools => OldSource/Tools}/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotGetAttachment/BakaShrotGetAttachment.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotGetMessages/BakaShrotGetMessages.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotList/BakaShrotList.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotList/BakaShrotList.pb.cfg (100%) rename {Tools => OldSource/Tools}/BakaShrotPushMessage/BakaShrotPushMessage.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotQuery/BakaShrotQuery.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotResolveIds/BakaShrotResolveIds.pb (100%) rename {Tools => OldSource/Tools}/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg (100%) rename {Tools => OldSource/Tools}/Common/ToolClient.pbi (100%) rename {Tools => OldSource/Tools}/Common/ToolConsole.pbi (100%) create mode 100644 Source/.cargo/config.toml create mode 100644 Source/.gitattributes create mode 100644 Source/Cargo.lock create mode 100644 Source/Cargo.toml create mode 100644 Source/README.md create mode 100644 Source/bindings/c/bakashrot.h create mode 100644 Source/bindings/purebasic/BakaShrot_Client_Prototypes.pbi create mode 100644 Source/bindings/purebasic/BakaShrot_ErrorCodes.pbi create mode 100644 Source/bindings/python/bakashrot.py create mode 100644 Source/bindings/python/check_bakashrot.py create mode 100644 Source/check.ps1 create mode 100644 Source/crates/bakashrot-capi/Cargo.toml create mode 100644 Source/crates/bakashrot-capi/cbindgen.toml create mode 100644 Source/crates/bakashrot-capi/src/lib.rs create mode 100644 Source/crates/bakashrot-capi/src/text.rs create mode 100644 Source/crates/bakashrot-capi/tests/common/mod.rs create mode 100644 Source/crates/bakashrot-capi/tests/exports.rs create mode 100644 Source/crates/bakashrot-capi/tests/header.rs create mode 100644 Source/crates/bakashrot-capi/tests/python.rs create mode 100644 Source/crates/bakashrot-client/Cargo.toml create mode 100644 Source/crates/bakashrot-client/src/lib.rs create mode 100644 Source/crates/bakashrot-config/Cargo.toml create mode 100644 Source/crates/bakashrot-config/example.toml create mode 100644 Source/crates/bakashrot-config/src/lib.rs create mode 100644 Source/crates/bakashrot-config/src/roles.rs create mode 100644 Source/crates/bakashrot-config/src/values.rs create mode 100644 Source/crates/bakashrot-config/tests/config.rs create mode 100644 Source/crates/bakashrot-pki/Cargo.toml create mode 100644 Source/crates/bakashrot-pki/src/ca.rs create mode 100644 Source/crates/bakashrot-pki/src/identity.rs create mode 100644 Source/crates/bakashrot-pki/src/lib.rs create mode 100644 Source/crates/bakashrot-pki/src/revocation.rs create mode 100644 Source/crates/bakashrot-pki/src/tls.rs create mode 100644 Source/crates/bakashrot-pki/tests/ca.rs create mode 100644 Source/crates/bakashrot-pki/tests/tls.rs create mode 100644 Source/crates/bakashrot-proto/Cargo.toml create mode 100644 Source/crates/bakashrot-proto/src/error.rs create mode 100644 Source/crates/bakashrot-proto/src/frame.rs create mode 100644 Source/crates/bakashrot-proto/src/lib.rs create mode 100644 Source/crates/bakashrot-proto/src/limits.rs create mode 100644 Source/crates/bakashrot-proto/src/names.rs create mode 100644 Source/crates/bakashrot-proto/src/packets/attachments.rs create mode 100644 Source/crates/bakashrot-proto/src/packets/messages.rs create mode 100644 Source/crates/bakashrot-proto/src/packets/mod.rs create mode 100644 Source/crates/bakashrot-proto/src/packets/replication.rs create mode 100644 Source/crates/bakashrot-proto/src/packets/session.rs create mode 100644 Source/crates/bakashrot-proto/tests/packets.rs create mode 100644 Source/crates/bakashrot-server/Cargo.toml create mode 100644 Source/crates/bakashrot-server/src/connection.rs create mode 100644 Source/crates/bakashrot-server/src/lib.rs create mode 100644 Source/crates/bakashrot-server/src/main.rs create mode 100644 Source/crates/bakashrot-server/src/retention.rs create mode 100644 Source/crates/bakashrot-server/src/writer.rs create mode 100644 Source/crates/bakashrot-server/tests/end_to_end.rs create mode 100644 Source/crates/bakashrot-storage/Cargo.toml create mode 100644 Source/crates/bakashrot-storage/src/batch.rs create mode 100644 Source/crates/bakashrot-storage/src/database.rs create mode 100644 Source/crates/bakashrot-storage/src/lib.rs create mode 100644 Source/crates/bakashrot-storage/src/query.rs create mode 100644 Source/crates/bakashrot-storage/src/reader.rs create mode 100644 Source/crates/bakashrot-storage/src/schema_v9.sql create mode 100644 Source/crates/bakashrot-storage/tests/storage.rs create mode 100644 Source/crates/bakashrot-tools/Cargo.toml create mode 100644 Source/crates/bakashrot-tools/src/bin/bakashrot-cert.rs create mode 100644 Source/crates/bakashrot-tools/src/bin/bakashrot.rs create mode 100644 Source/crates/bakashrot-tools/tests/bakashrot.rs create mode 100644 Source/crates/bakashrot-tools/tests/cert.rs create mode 100644 Source/docs/certificates.md create mode 100644 Source/docs/client.md create mode 100644 Source/docs/config.md create mode 100644 Source/docs/oid.md create mode 100644 Source/docs/protocol.md create mode 100644 Source/docs/server.md create mode 100644 Source/docs/storage.md create mode 100644 Source/rust-toolchain.toml create mode 100644 revamp.md diff --git a/.github/workflows/source.yml b/.github/workflows/source.yml new file mode 100644 index 0000000..800f6b5 --- /dev/null +++ b/.github/workflows/source.yml @@ -0,0 +1,30 @@ +# The new sources (Source/): the same checks as Source/check.ps1, on Windows +# and Linux. Gitea Actions runs this file too. +name: Source + +on: + push: + paths: ["Source/**", ".github/workflows/source.yml"] + pull_request: + paths: ["Source/**", ".github/workflows/source.yml"] + +jobs: + check: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + working-directory: Source + steps: + - uses: actions/checkout@v4 + # Installs the toolchain Source/rust-toolchain.toml pins. + - run: rustup toolchain install + - run: cargo fmt --all -- --check + - run: cargo clippy --workspace --all-targets --all-features -- -D warnings + - run: cargo test --workspace --all-features + - run: cargo doc --workspace --no-deps --all-features + env: + RUSTDOCFLAGS: -D warnings diff --git a/.gitignore b/.gitignore index 4b71ce2..6ab3666 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,8 @@ # Build Artifacts *.exe *.dll -# ... except the runtime redistributables the release packages, see Libs/redist/README.md -!Libs/redist/**/*.dll +# ... except the runtime redistributables the old release packages, see OldSource/Libs/redist/README.md +!OldSource/Libs/redist/**/*.dll *.so *.a *.pdb @@ -22,7 +22,10 @@ Release/ # Python __pycache__/ +# Rust (Source/) +target/ + # The examples run their server in their own folder: its database, and # what their client scripts write -Examples/**/*.sqlite* -Examples/**/out/ +OldSource/Examples/**/*.sqlite* +OldSource/Examples/**/out/ diff --git a/.gitmodules b/.gitmodules index e8a3d2b..2ad491a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "Includes/PB-MessagePack"] - path = Includes/PB-MessagePack + path = OldSource/Includes/PB-MessagePack url = https://github.com/aziascreations/PB-MessagePack.git diff --git a/CLAUDE.md b/CLAUDE.md index ea671b2..73793c4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,116 +1,46 @@ # BakaShrot - start here -A message store with replication, in PureBasic: servers take JSON (or any) -messages per topic/node from authenticated clients, store them in SQLite, -and replicate them between peers by name. Clients: a DLL, CLI tools, a -Python module. An **internal tool on trusted machines**: correctness and -operations come before security hardening (`Notes.md`, "Threat model"). +A message store with replication: servers take messages per topic/node +from authenticated clients, store them in SQLite, and replicate them +between peers by name. Clients: a C DLL, CLI tools, a Python module. An +**internal tool on trusted machines**. -## Read first +**Being rewritten in Rust** (since 2026-11-13): -1. `Notes.md`: "Right now" (what's committed, what's next), where things - stand, "Open items, by importance" (the to-do list), "Testing tips". -2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, - code conventions), `Attachments.md`, `Cryptography.md`, - `StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`, - `Suggestions.md`. -3. `git log --oneline` and `git status`: what's committed. Work happens on - branches off `master` (`timestamps-retention` at this writing). +- `revamp.md`: why, what's decided, what's proposed and open, the plan and + its status. Read it first. +- `Source/`: the new implementation (`Source/README.md`: layout, commands, + conventions; `Source/docs/`: designs, `protocol.md` first). +- `OldSource/`: the old PureBasic implementation, the reference for the + behaviour to carry over. It has its own `CLAUDE.md` (build, test, traps), + `Notes.md` and `Design/`; its paths are relative to `OldSource/`. -## Build +## Toolchain -- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe /EXE [flags]`. - Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe /OUTPUT /OPTIMIZER`. - Code must compile with both (`Release.ps1` checks the 6.40 side). -- `Build.ps1` builds everything into `Build\`, **regenerates keys and - configs, then runs a server waiting on its console**: don't run it from - an automated shell. To rebuild after a change, compile what changed: - -| Source | Output | Flags | -|---|---|---| -| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` | -| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` | -| `Tools\\.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\.exe` | `/CONSOLE` | -| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` | -| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` | -| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` | -| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb` | `Build\` | `/CONSOLE` | -| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` | - -- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and - smoke-tests it (`-Force` replaces an existing folder of the same name). -- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with - `libsodium-dev`. `Docker/Server/` builds the server image, on the - PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3; - needs a `docker login`), see its Dockerfile. - -## Test - -Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a -fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means -all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: - -| Suite | Ports | Covers | -|---|---|---| -| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name | -| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors | -| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` | -| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) | -| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | -| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | -| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | -| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) | - -Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and -the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` -(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous = -FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every -suite: they take a few minutes in all. - -## Traps - -- **Run exes from `Build\`**: the antivirus blocks them in temp folders. -- **`Build\` holds private keys**: git-ignored, never publish it. The one - exception: `Examples/*/` commit their configs, keys included, on purpose - (public, example-only, marked so); don't copy those keys anywhere else. -- **PureBasic is single pass**: constants, structures and procedures must - be declared before use, so include order matters (e.g. `Config.pbi` - includes `Packets.pbi` for its constants). -- **`SetDatabase*()` binds the next statement run on that connection**, not - a specific one: set them right before their `DatabaseUpdate/Query`. -- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on - the stack, the jump corrupts it (a config error crashed the server with - 0xC0000005). Set the error, leave the `Select`, then jump. Out of - `For`/`ForEach`/`While` loops is fine (checked on both compilers). -- **PureBasic lists aren't safe to walk from several threads** (`ForEach` - moves the shared current element): give each thread its own copy. -- **Files mix CRLF and LF**: edits must keep each file's line endings. -- **PowerShell 5**: JSON passed as an argument loses its double quotes - (tests write it to a file, `@file`), and `@()` can't be passed through - `-File`. -- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: - write edit scripts to files, or use the Edit tool. -- **The real server needs a console on Windows** (it stops at once without - input): tests use `BenchServer.exe` and its stop file instead. On Linux - it runs on without one, SIGTERM/SIGINT stop it. +- Rust via rustup, in `%USERPROFILE%\.cargo\bin`, which **isn't on every + shell's PATH**: prepend it (`export PATH="$HOME/.cargo/bin:$PATH"` in + bash; `check.ps1` does it itself). The toolchain is pinned + (`Source/rust-toolchain.toml`, 1.100.0, MSVC; Visual Studio 18 has the + linker). +- `Source\check.ps1` runs what CI runs; it must pass before a step is done. +- PureBasic 5.73 and 6.40 for `OldSource/`, see `OldSource/CLAUDE.md`. ## Working rules -- **Commit only when the owner asks**, on a branch, not `master`. -- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at - this writing); any difference refuses the connection. -- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this - writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), - existing databases must keep working. -- **Packets** follow `Design/Packets.md` "Code conventions": one file per - packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and - `_Free` when it holds data), every field validated on decode. -- **Every write goes through the writer** (`Server/Storage/Writer.pbi`, - under its mutex); reads use the thread's own connection. -- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`, - like PB-MessagePack's): name, version (0.0.1 at this writing), tested - compilers. A release bumps the version in all of them; only list a - compiler/platform once every suite passed with it. -- **Docs follow the code**: a finished piece gets a "Done: ... (date)" - section in `Notes.md`, what's left goes to its open items, and the - `Design/` doc of that area is updated with it. +- **Commit only when the owner asks**, on a branch (`revamp`), not `master`. +- **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its + tests pass and its docs are updated, then its status goes in the table. +- **`OldSource/` is the reference:** don't change it beyond keeping it + building and passing, unless asked. +- **Decisions go in `revamp.md`**: moved to "Decided" only when the owner + decides, with the date. +- **Use existing crates** rather than reimplementing (MessagePack is `rmp-serde`). +- **Files mix CRLF and LF:** edits must keep each file's line endings + (`Source/` is LF, the docs at the root and in `OldSource/` mostly CRLF). +- **Bash tool heredocs collapse `\\`:** write edit scripts to files, or use + the Edit tool. +- **Run exes from a build folder** (`OldSource\Build\`, `Source\target\`): + the antivirus blocks them in temp folders. +- **Generated keys and certificates never go in git** (`Build/`, + `target/`). The one exception: `OldSource/Examples/*/` commit theirs on + purpose (public, example-only, marked so). diff --git a/Build.ps1 b/OldSource/Build.ps1 similarity index 100% rename from Build.ps1 rename to OldSource/Build.ps1 diff --git a/OldSource/CLAUDE.md b/OldSource/CLAUDE.md new file mode 100644 index 0000000..5b460ef --- /dev/null +++ b/OldSource/CLAUDE.md @@ -0,0 +1,121 @@ +# BakaShrot, the old PureBasic implementation - start here + +**Frozen since 2026-11-13** as the reference for the Rust rewrite +(`../revamp.md`, `../CLAUDE.md`). Every path below is relative to this +folder, `OldSource/`: run the scripts and compilers from here. + +A message store with replication, in PureBasic: servers take JSON (or any) +messages per topic/node from authenticated clients, store them in SQLite, +and replicate them between peers by name. Clients: a DLL, CLI tools, a +Python module. An **internal tool on trusted machines**: correctness and +operations come before security hardening (`Notes.md`, "Threat model"). + +## Read first + +1. `Notes.md`: "Right now" (what's committed, what's next), where things + stand, "Open items, by importance" (the to-do list), "Testing tips". +2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, + code conventions), `Attachments.md`, `Cryptography.md`, + `Certificates.md`, `StorageConcurrency.md`, `ReplicationIssues.md`, + `Release.md`, `Suggestions.md`. +3. `git log --oneline` and `git status`: what's committed. Work happens on + branches off `master` (`timestamps-retention` at this writing). + +## Build + +- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe /EXE [flags]`. + Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe /OUTPUT /OPTIMIZER`. + Code must compile with both (`Release.ps1` checks the 6.40 side). +- `Build.ps1` builds everything into `Build\`, **regenerates keys and + configs, then runs a server waiting on its console**: don't run it from + an automated shell. To rebuild after a change, compile what changed: + +| Source | Output | Flags | +|---|---|---| +| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` | +| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` | +| `Tools\\.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\.exe` | `/CONSOLE` | +| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` | +| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` | +| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` | +| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb`, `Tests\X509Test.pb` | `Build\` | `/CONSOLE` | +| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` | + +- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and + smoke-tests it (`-Force` replaces an existing folder of the same name). +- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with + `libsodium-dev`. `Docker/Server/` builds the server image, on the + PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3; + needs a `docker login`), see its Dockerfile. + +## Test + +Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a +fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means +all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: + +| Suite | Ports | Covers | +|---|---|---| +| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name | +| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors | +| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` | +| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) | +| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | +| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | +| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | +| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) | +| `X509-Test.ps1` | none | X.509 certificates (`X509Test.exe`), both ways with OpenSSL when it's there (Git's) | + +Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and +the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` +(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous = +FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every +suite: they take a few minutes in all. + +## Traps + +- **Run exes from `Build\`**: the antivirus blocks them in temp folders. +- **`Build\` holds private keys**: git-ignored, never publish it. The one + exception: `Examples/*/` commit their configs, keys included, on purpose + (public, example-only, marked so); don't copy those keys anywhere else. +- **PureBasic is single pass**: constants, structures and procedures must + be declared before use, so include order matters (e.g. `Config.pbi` + includes `Packets.pbi` for its constants). +- **`SetDatabase*()` binds the next statement run on that connection**, not + a specific one: set them right before their `DatabaseUpdate/Query`. +- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on + the stack, the jump corrupts it (a config error crashed the server with + 0xC0000005). Set the error, leave the `Select`, then jump. Out of + `For`/`ForEach`/`While` loops is fine (checked on both compilers). +- **PureBasic lists aren't safe to walk from several threads** (`ForEach` + moves the shared current element): give each thread its own copy. +- **Files mix CRLF and LF**: edits must keep each file's line endings. +- **PowerShell 5**: JSON passed as an argument loses its double quotes + (tests write it to a file, `@file`), and `@()` can't be passed through + `-File`. +- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: + write edit scripts to files, or use the Edit tool. +- **The real server needs a console on Windows** (it stops at once without + input): tests use `BenchServer.exe` and its stop file instead. On Linux + it runs on without one, SIGTERM/SIGINT stop it. + +## Working rules + +- **Commit only when the owner asks**, on a branch, not `master`. +- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at + this writing); any difference refuses the connection. +- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this + writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), + existing databases must keep working. +- **Packets** follow `Design/Packets.md` "Code conventions": one file per + packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and + `_Free` when it holds data), every field validated on decode. +- **Every write goes through the writer** (`Server/Storage/Writer.pbi`, + under its mutex); reads use the thread's own connection. +- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`, + like PB-MessagePack's): name, version (0.0.1 at this writing), tested + compilers. A release bumps the version in all of them; only list a + compiler/platform once every suite passed with it. +- **Docs follow the code**: a finished piece gets a "Done: ... (date)" + section in `Notes.md`, what's left goes to its open items, and the + `Design/` doc of that area is updated with it. diff --git a/Client/BakaShrot_Client.pbi b/OldSource/Client/BakaShrot_Client.pbi similarity index 100% rename from Client/BakaShrot_Client.pbi rename to OldSource/Client/BakaShrot_Client.pbi diff --git a/Client/BakaShrot_Client.pbi.cfg b/OldSource/Client/BakaShrot_Client.pbi.cfg similarity index 100% rename from Client/BakaShrot_Client.pbi.cfg rename to OldSource/Client/BakaShrot_Client.pbi.cfg diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/OldSource/Client/BakaShrot_Client_Prototypes.pbi similarity index 100% rename from Client/BakaShrot_Client_Prototypes.pbi rename to OldSource/Client/BakaShrot_Client_Prototypes.pbi diff --git a/Client/BakaShrot_ErrorCodes.pbi b/OldSource/Client/BakaShrot_ErrorCodes.pbi similarity index 100% rename from Client/BakaShrot_ErrorCodes.pbi rename to OldSource/Client/BakaShrot_ErrorCodes.pbi diff --git a/Client/notes.txt b/OldSource/Client/notes.txt similarity index 100% rename from Client/notes.txt rename to OldSource/Client/notes.txt diff --git a/OldSource/Commons/Console.pbi b/OldSource/Commons/Console.pbi new file mode 100644 index 0000000..e69de29 diff --git a/Commons/Cryptography/Cipher.pbi b/OldSource/Commons/Cryptography/Cipher.pbi similarity index 100% rename from Commons/Cryptography/Cipher.pbi rename to OldSource/Commons/Cryptography/Cipher.pbi diff --git a/OldSource/Commons/Cryptography/Der.pbi b/OldSource/Commons/Cryptography/Der.pbi new file mode 100644 index 0000000..a92f4a2 --- /dev/null +++ b/OldSource/Commons/Cryptography/Der.pbi @@ -0,0 +1,1084 @@ +;{- Code Header +; ==- Basic Info -================================ +; Name: Der.pbi +; Version: 0.0.1 +; Author: Herwin Bozet (NibblePoker) +; +; ==- Compatibility -============================= +; Tested compiler versions: +; * PureBasic 5.73 LTS (Windows x64) +; * PureBasic 6.40 C Backend (Windows x64) +; +; ==- Links -===================================== +; GitHub: https://github.com/aziascreations/BakaShrot +;} + +; ============================================================================ +; BakaShrot DER +; +; Reading and writing ASN.1 DER, the encoding of X.509 certificates, for +; Commons/Cryptography/X509.pbi. Only what certificates use: universal +; tags, context tags [0]-[30], lengths up to #BakaShrot_Der_MaxSize. +; +; Reading is strict, anything that isn't DER is refused: +; - definite lengths only, in their shortest form, +; - tag numbers under 31 (one identifier byte), +; - integers in their shortest form, booleans $00 or $FF, +; - OIDs without padded arcs, times as UTCTime "YYMMDDHHMMSSZ" or +; GeneralizedTime "YYYYMMDDHHMMSSZ" (UTC, whole seconds, real dates), +; - strings without a NUL, PrintableString and IA5String in ASCII. +; A reader never reads past its end: element and contents sizes are checked +; before anything is read. +; +; Reading: a BakaShrot_DerReader walks the elements of a buffer, or of a +; constructed element's contents (BakaShrot_Der_ReaderOf()). Once a read +; fails, the reader stays failed. The elements point into the buffer read, +; which must outlive them. +; +; Writing: a BakaShrot_DerWriter appends elements to a buffer it grows; +; BakaShrot_Der_Begin()/_End() wrap what's written between them in a +; constructed element (SEQUENCE, SET, [n], or an OCTET STRING holding DER). +; Once a write fails the writer stays failed, BakaShrot_Der_Finish() gives +; the result or 0. +; +; Times are seconds since 1970-01-01 00:00:00 UTC, years 0000 to 9999. +; OIDs are dotted text ("1.3.101.112"), arcs of any size up to 140 bits +; (2.25. OIDs have 128-bit arcs). +; +; No globals: any number of threads, each with its own readers and writers. +; ============================================================================ + + +; Universal tags, as their whole identifier byte. +#BakaShrot_Der_Boolean = $01 +#BakaShrot_Der_Integer = $02 +#BakaShrot_Der_BitString = $03 +#BakaShrot_Der_OctetString = $04 +#BakaShrot_Der_Null = $05 +#BakaShrot_Der_Oid = $06 +#BakaShrot_Der_Utf8String = $0C +#BakaShrot_Der_PrintableString = $13 +#BakaShrot_Der_T61String = $14 +#BakaShrot_Der_Ia5String = $16 +#BakaShrot_Der_UtcTime = $17 +#BakaShrot_Der_GeneralizedTime = $18 +#BakaShrot_Der_BmpString = $1E +#BakaShrot_Der_Sequence = $30 +#BakaShrot_Der_Set = $31 + +; Context-specific tags: #BakaShrot_Der_Context | n for a primitive [n] +; (IMPLICIT of a primitive type), #BakaShrot_Der_ContextConstructed | n for +; a constructed one (EXPLICIT, or IMPLICIT of a constructed type). +#BakaShrot_Der_Context = $80 +#BakaShrot_Der_ContextConstructed = $A0 + +; Biggest element read or written, far more than any certificate. +#BakaShrot_Der_MaxSize = $1000000 + +; Most constructed elements a writer keeps open at once. +#BakaShrot_Der_MaxDepth = 16 + +; Longest OID arc, encoded: 20 bytes of 7 bits, 140 bits. +#BakaShrot_Der_MaxArcBytes = 20 + +; Longest OID arc in decimal digits (2^140 has 43; DecimalToArc() refuses +; what still takes more than 20 bytes). +#BakaShrot_Der_MaxArcDigits = 43 + + +; An element read: its whole identifier byte, where it starts, its size +; with its header, and its contents. +Structure BakaShrot_DerElement + Tag.i + *Start + Size.i + *Content + ContentSize.i +EndStructure + + +Structure BakaShrot_DerReader + *Position + *End + Failed.i +EndStructure + + +Structure BakaShrot_DerWriter + *Buffer + Capacity.i + Size.i + ; The constructed elements begun and not ended yet: where their contents + ; start in Buffer, and their tags. + Depth.i + Starts.i[#BakaShrot_Der_MaxDepth] + Tags.i[#BakaShrot_Der_MaxDepth] + Failed.i +EndStructure + + +;- Reading + +; Reads Size bytes at *Data. +Procedure BakaShrot_Der_InitReader(*Reader.BakaShrot_DerReader, *Data, Size.i) + *Reader\Position = *Data + *Reader\End = *Data + *Reader\Failed = #True + If *Data And Size >= 0 + *Reader\End = *Data + Size + *Reader\Failed = #False + EndIf +EndProcedure + + +; Reads the contents of *Element (a SEQUENCE, a SET, an EXPLICIT [n]...). +Procedure BakaShrot_Der_ReaderOf(*Reader.BakaShrot_DerReader, *Element.BakaShrot_DerElement) + BakaShrot_Der_InitReader(*Reader, *Element\Content, *Element\ContentSize) +EndProcedure + + +; #True once everything was read, and nothing failed. +Procedure.i BakaShrot_Der_AtEnd(*Reader.BakaShrot_DerReader) + ProcedureReturn Bool(Not *Reader\Failed And *Reader\Position = *Reader\End) +EndProcedure + + +; The identifier byte of the next element, -1 at the end or once failed. +; Doesn't move: for OPTIONAL and DEFAULT elements. +Procedure.i BakaShrot_Der_PeekTag(*Reader.BakaShrot_DerReader) + If *Reader\Failed Or *Reader\Position >= *Reader\End + ProcedureReturn -1 + EndIf + ProcedureReturn PeekA(*Reader\Position) +EndProcedure + + +; Reads the next element, whatever its tag, into *Element. +; Returns #False, and the reader fails, at the end or if it isn't DER. +Procedure.i BakaShrot_Der_Read(*Reader.BakaShrot_DerReader, *Element.BakaShrot_DerElement) + Protected *P, Left.i, Tag.i, First.i, Count.i, Length.q, i.i + + If *Reader\Failed + ProcedureReturn #False + EndIf + *P = *Reader\Position + Left = *Reader\End - *P + If Left < 2 + Goto ReadFailed + EndIf + + ; High tag numbers (31 and up) take more bytes, certificates never use them. + Tag = PeekA(*P) + If (Tag & $1F) = $1F + Goto ReadFailed + EndIf + + First = PeekA(*P + 1) + If First < $80 + Length = First + Count = 0 + ElseIf First = $80 Or First > $84 + ; Indefinite (BER only), or over 4 bytes of length. + Goto ReadFailed + Else + Count = First & $7F + If Left < 2 + Count + Goto ReadFailed + EndIf + ; The shortest form only: no leading zero, the long form from 128 on. + If PeekA(*P + 2) = 0 + Goto ReadFailed + EndIf + Length = 0 + For i = 0 To Count - 1 + Length = (Length << 8) | PeekA(*P + 2 + i) + Next + If Length < $80 + Goto ReadFailed + EndIf + EndIf + + If Length > #BakaShrot_Der_MaxSize Or Length > Left - 2 - Count + Goto ReadFailed + EndIf + + *Element\Tag = Tag + *Element\Start = *P + *Element\Content = *P + 2 + Count + *Element\ContentSize = Length + *Element\Size = 2 + Count + Length + *Reader\Position = *P + *Element\Size + ProcedureReturn #True + + ReadFailed: + *Reader\Failed = #True + ProcedureReturn #False +EndProcedure + + +; Reads the next element, which must have Tag, into *Element. +; Returns #False, and the reader fails, otherwise. +Procedure.i BakaShrot_Der_Expect(*Reader.BakaShrot_DerReader, Tag.i, *Element.BakaShrot_DerElement) + If Not BakaShrot_Der_Read(*Reader, *Element) + ProcedureReturn #False + EndIf + If *Element\Tag <> Tag + *Reader\Failed = #True + ProcedureReturn #False + EndIf + ProcedureReturn #True +EndProcedure + + +; #True if *Element's contents are a DER integer: at least a byte, and no +; leading byte that only repeats the sign. Any size. +Procedure.i BakaShrot_Der_IsMinimalInteger(*Element.BakaShrot_DerElement) + Protected *C = *Element\Content + + If *Element\ContentSize < 1 + ProcedureReturn #False + EndIf + If *Element\ContentSize > 1 + If (PeekA(*C) = $00 And PeekA(*C + 1) < $80) Or (PeekA(*C) = $FF And PeekA(*C + 1) >= $80) + ProcedureReturn #False + EndIf + EndIf + ProcedureReturn #True +EndProcedure + + +; An integer of up to 8 bytes into *Value\q (signed). +Procedure.i BakaShrot_Der_GetInteger(*Element.BakaShrot_DerElement, *Value.Quad) + Protected *C = *Element\Content, Value.q, i.i + + If *Element\ContentSize > 8 Or Not BakaShrot_Der_IsMinimalInteger(*Element) + ProcedureReturn #False + EndIf + ; The first byte sign-extended, then the others. + Value = PeekB(*C) + For i = 1 To *Element\ContentSize - 1 + Value = (Value << 8) | PeekA(*C + i) + Next + *Value\q = Value + ProcedureReturn #True +EndProcedure + + +; A BOOLEAN into *Value\i, #True or #False. +Procedure.i BakaShrot_Der_GetBoolean(*Element.BakaShrot_DerElement, *Value.Integer) + If *Element\ContentSize <> 1 + ProcedureReturn #False + EndIf + Select PeekA(*Element\Content) + Case $00 + *Value\i = #False + Case $FF + *Value\i = #True + Default + ProcedureReturn #False + EndSelect + ProcedureReturn #True +EndProcedure + + +; A BIT STRING of whole bytes (keys, signatures): *Bytes\i points to them in +; the element, *Size\i is how many. +Procedure.i BakaShrot_Der_GetBitStringBytes(*Element.BakaShrot_DerElement, *Bytes.Integer, *Size.Integer) + If *Element\ContentSize < 1 Or PeekA(*Element\Content) <> 0 + ProcedureReturn #False + EndIf + *Bytes\i = *Element\Content + 1 + *Size\i = *Element\ContentSize - 1 + ProcedureReturn #True +EndProcedure + + +; A BIT STRING of named bits (KeyUsage) as flags: bit n of the string, the +; first one being 0, is 1 << n. Up to 32 bits. +Procedure.i BakaShrot_Der_GetBitFlags(*Element.BakaShrot_DerElement, *Flags.Integer) + Protected *C = *Element\Content, Size.i = *Element\ContentSize, Unused.i, Flags.i, i.i, Bit.i, Byte.i + + If Size < 1 Or Size > 5 + ProcedureReturn #False + EndIf + Unused = PeekA(*C) + If Unused > 7 Or (Size = 1 And Unused <> 0) + ProcedureReturn #False + EndIf + ; The unused bits of the last byte must be zero. + If Size > 1 And (PeekA(*C + Size - 1) & ((1 << Unused) - 1)) <> 0 + ProcedureReturn #False + EndIf + For i = 1 To Size - 1 + Byte = PeekA(*C + i) + For Bit = 0 To 7 + If Byte & ($80 >> Bit) + Flags = Flags | (1 << ((i - 1) * 8 + Bit)) + EndIf + Next + Next + *Flags\i = Flags + ProcedureReturn #True +EndProcedure + + +;- OIDs + +; #True if Text is one or more digits, without a leading zero (but "0"). +Procedure.i BakaShrot_Der_IsDecimal(Text.s) + Protected i.i, c.i + + If Text = "" Or Len(Text) > #BakaShrot_Der_MaxArcDigits Or (Len(Text) > 1 And Left(Text, 1) = "0") + ProcedureReturn #False + EndIf + For i = 1 To Len(Text) + c = Asc(Mid(Text, i, 1)) + If c < '0' Or c > '9' + ProcedureReturn #False + EndIf + Next + ProcedureReturn #True +EndProcedure + + +; The arc in Count bytes of base-128 groups at *P, in decimal. +Procedure.s BakaShrot_Der_ArcToDecimal(*P, Count.i) + Protected Dim Digits.a(63) + Protected Length.i = 1, i.i, j.i, Carry.i, x.i, Text.s + + ; Digits(), least significant first: times 128 plus the group, per group. + For i = 0 To Count - 1 + Carry = PeekA(*P + i) & $7F + For j = 0 To Length - 1 + x = Digits(j) * 128 + Carry + Digits(j) = x % 10 + Carry = x / 10 + Next + While Carry + Digits(Length) = Carry % 10 + Carry = Carry / 10 + Length + 1 + Wend + Next + For j = Length - 1 To 0 Step -1 + Text + Chr('0' + Digits(j)) + Next + ProcedureReturn Text +EndProcedure + + +; Writes the arc Decimal (BakaShrot_Der_IsDecimal()) as base-128 groups at +; *Out (#BakaShrot_Der_MaxArcBytes bytes), the high bit on all but the last. +; Returns how many bytes, 0 if it takes more than #BakaShrot_Der_MaxArcBytes. +Procedure.i BakaShrot_Der_DecimalToArc(Decimal.s, *Out) + Protected Dim Groups.a(#BakaShrot_Der_MaxArcBytes) + Protected Count.i, Quotient.s, Remainder.i, Current.i, Digit.i, i.i + + ; Divides by 128 until nothing's left, the remainders least significant first. + Repeat + Quotient = "" + Remainder = 0 + For i = 1 To Len(Decimal) + Current = Remainder * 10 + (Asc(Mid(Decimal, i, 1)) - '0') + Digit = Current / 128 + Remainder = Current % 128 + If Digit > 0 Or Quotient <> "" + Quotient + Chr('0' + Digit) + EndIf + Next + If Count >= #BakaShrot_Der_MaxArcBytes + ProcedureReturn 0 + EndIf + Groups(Count) = Remainder + Count + 1 + Decimal = Quotient + Until Decimal = "" + + For i = 0 To Count - 1 + If i < Count - 1 + PokeA(*Out + i, Groups(Count - 1 - i) | $80) + Else + PokeA(*Out + i, Groups(Count - 1 - i)) + EndIf + Next + ProcedureReturn Count +EndProcedure + + +; Writes the DER contents of the OID Oid ("1.3.101.112") at *Out, OutSize +; bytes. Returns their size, 0 if Oid isn't a valid OID or doesn't fit. +; Valid: two arcs or more, each digits without a leading zero, the first 0, +; 1 or 2, the second under 40 after a 0 or 1. +Procedure.i BakaShrot_Der_EncodeOid(Oid.s, *Out, OutSize.i) + Protected Count.i, i.i, Arc.s, First.q, Second.q, Size.i, Written.i + Protected Dim ArcBytes.a(#BakaShrot_Der_MaxArcBytes) + + Count = CountString(Oid, ".") + 1 + If Count < 2 + ProcedureReturn 0 + EndIf + For i = 1 To Count + If Not BakaShrot_Der_IsDecimal(StringField(Oid, i, ".")) + ProcedureReturn 0 + EndIf + Next + + ; The first two arcs share one: 40 * First + Second, kept within a quad. + First = Val(StringField(Oid, 1, ".")) + Arc = StringField(Oid, 2, ".") + If First > 2 Or Len(Arc) > 17 + ProcedureReturn 0 + EndIf + Second = Val(Arc) + If First < 2 And Second >= 40 + ProcedureReturn 0 + EndIf + + For i = 2 To Count + If i = 2 + Arc = Str(40 * First + Second) + Else + Arc = StringField(Oid, i, ".") + EndIf + Written = BakaShrot_Der_DecimalToArc(Arc, @ArcBytes(0)) + If Written = 0 Or Size + Written > OutSize + ProcedureReturn 0 + EndIf + CopyMemory(@ArcBytes(0), *Out + Size, Written) + Size + Written + Next + ProcedureReturn Size +EndProcedure + + +; #True if Oid is a valid OID's dotted text, see BakaShrot_Der_EncodeOid(). +Procedure.i BakaShrot_Der_IsValidOid(Oid.s) + Protected *Buffer, Size.i + + *Buffer = AllocateMemory((CountString(Oid, ".") + 1) * #BakaShrot_Der_MaxArcBytes) + If Not *Buffer + ProcedureReturn #False + EndIf + Size = BakaShrot_Der_EncodeOid(Oid, *Buffer, MemorySize(*Buffer)) + FreeMemory(*Buffer) + ProcedureReturn Bool(Size > 0) +EndProcedure + + +; An OBJECT IDENTIFIER's dotted text, "" if it isn't a valid one. +Procedure.s BakaShrot_Der_GetOid(*Element.BakaShrot_DerElement) + Protected *C = *Element\Content, Size.i = *Element\ContentSize + Protected i.i, Start.i, Text.s, First.q + + ; Each arc: base-128 groups, the high bit on all of them but the last, + ; no padding group ($80) first. + If Size < 1 Or (PeekA(*C + Size - 1) & $80) <> 0 + ProcedureReturn "" + EndIf + For i = 0 To Size - 1 + If i = Start And PeekA(*C + i) = $80 + ProcedureReturn "" + EndIf + If (PeekA(*C + i) & $80) = 0 + If i - Start + 1 > #BakaShrot_Der_MaxArcBytes + ProcedureReturn "" + EndIf + If Start = 0 + ; The first two arcs, 40 * X + Y: kept within a quad (8 groups). + If i + 1 > 8 + ProcedureReturn "" + EndIf + First = Val(BakaShrot_Der_ArcToDecimal(*C, i + 1)) + If First < 40 + Text = "0." + Str(First) + ElseIf First < 80 + Text = "1." + Str(First - 40) + Else + Text = "2." + Str(First - 80) + EndIf + Else + Text + "." + BakaShrot_Der_ArcToDecimal(*C + Start, i - Start + 1) + EndIf + Start = i + 1 + EndIf + Next + ProcedureReturn Text +EndProcedure + + +;- Times + +; Days since 1970-01-01 of a date of the proleptic Gregorian calendar +; (Howard Hinnant's days_from_civil), any time zone or locale aside. +Procedure.q BakaShrot_Der_DaysFromCivil(Year.q, Month.q, Day.q) + Protected Era.q, YearOfEra.q, DayOfYear.q, DayOfEra.q, M.q + + If Month <= 2 + Year - 1 + M = Month + 9 + Else + M = Month - 3 + EndIf + If Year >= 0 + Era = Year / 400 + Else + Era = (Year - 399) / 400 + EndIf + YearOfEra = Year - Era * 400 + DayOfYear = (153 * M + 2) / 5 + Day - 1 + DayOfEra = YearOfEra * 365 + YearOfEra / 4 - YearOfEra / 100 + DayOfYear + ProcedureReturn Era * 146097 + DayOfEra - 719468 +EndProcedure + + +; The date of Days since 1970-01-01, the other way (civil_from_days). +Procedure BakaShrot_Der_CivilFromDays(Days.q, *Year.Quad, *Month.Quad, *Day.Quad) + Protected Era.q, DayOfEra.q, YearOfEra.q, DayOfYear.q, Mp.q, Year.q, Month.q + + Days + 719468 + If Days >= 0 + Era = Days / 146097 + Else + Era = (Days - 146096) / 146097 + EndIf + DayOfEra = Days - Era * 146097 + YearOfEra = (DayOfEra - DayOfEra / 1460 + DayOfEra / 36524 - DayOfEra / 146096) / 365 + Year = YearOfEra + Era * 400 + DayOfYear = DayOfEra - (365 * YearOfEra + YearOfEra / 4 - YearOfEra / 100) + Mp = (5 * DayOfYear + 2) / 153 + *Day\q = DayOfYear - (153 * Mp + 2) / 5 + 1 + If Mp < 10 + Month = Mp + 3 + Else + Month = Mp - 9 + EndIf + If Month <= 2 + Year + 1 + EndIf + *Year\q = Year + *Month\q = Month +EndProcedure + + +; The number written by Count digits at *P, -1 if one isn't a digit. +Procedure.i BakaShrot_Der_ReadDigits(*P, Count.i) + Protected i.i, c.i, Value.i + + For i = 0 To Count - 1 + c = PeekA(*P + i) + If c < '0' Or c > '9' + ProcedureReturn -1 + EndIf + Value = Value * 10 + (c - '0') + Next + ProcedureReturn Value +EndProcedure + + +; A UTCTime or a GeneralizedTime into *Seconds\q, since 1970 UTC. +; UTCTime's years: 50-99 are 1950-1999, 00-49 are 2000-2049 (RFC 5280). +Procedure.i BakaShrot_Der_GetTime(*Element.BakaShrot_DerElement, *Seconds.Quad) + Protected *C = *Element\Content, Year.q, Month.q, Day.q, Hour.i, Minute.i, Second.i, Days.q + Protected CheckYear.q, CheckMonth.q, CheckDay.q + + If *Element\Tag = #BakaShrot_Der_UtcTime And *Element\ContentSize = 13 + Year = BakaShrot_Der_ReadDigits(*C, 2) + If Year < 0 + ProcedureReturn #False + ElseIf Year >= 50 + Year + 1900 + Else + Year + 2000 + EndIf + *C + 2 + ElseIf *Element\Tag = #BakaShrot_Der_GeneralizedTime And *Element\ContentSize = 15 + Year = BakaShrot_Der_ReadDigits(*C, 4) + If Year < 0 + ProcedureReturn #False + EndIf + *C + 4 + Else + ProcedureReturn #False + EndIf + + Month = BakaShrot_Der_ReadDigits(*C, 2) + Day = BakaShrot_Der_ReadDigits(*C + 2, 2) + Hour = BakaShrot_Der_ReadDigits(*C + 4, 2) + Minute = BakaShrot_Der_ReadDigits(*C + 6, 2) + Second = BakaShrot_Der_ReadDigits(*C + 8, 2) + If PeekA(*C + 10) <> 'Z' Or Month < 1 Or Month > 12 Or Day < 1 Or Day > 31 Or Hour < 0 Or Hour > 23 Or Minute < 0 Or Minute > 59 Or Second < 0 Or Second > 59 + ProcedureReturn #False + EndIf + + ; A real date: no 30th of February. + Days = BakaShrot_Der_DaysFromCivil(Year, Month, Day) + BakaShrot_Der_CivilFromDays(Days, @CheckYear, @CheckMonth, @CheckDay) + If CheckYear <> Year Or CheckMonth <> Month Or CheckDay <> Day + ProcedureReturn #False + EndIf + + *Seconds\q = Days * 86400 + Hour * 3600 + Minute * 60 + Second + ProcedureReturn #True +EndProcedure + + +;- Strings + +; A string's text into *Text\s: UTF8String, PrintableString, IA5String, +; T61String (taken as Latin-1) or BMPString (UTF-16BE). #False for another +; type, a NUL in it, or a PrintableString or IA5String that isn't ASCII. +Procedure.i BakaShrot_Der_GetText(*Element.BakaShrot_DerElement, *Text.String) + Protected *C = *Element\Content, Size.i = *Element\ContentSize, i.i, c.i, Text.s + + Select *Element\Tag + Case #BakaShrot_Der_Utf8String + For i = 0 To Size - 1 + If PeekA(*C + i) = 0 + ProcedureReturn #False + EndIf + Next + If Size > 0 + Text = PeekS(*C, Size, #PB_UTF8 | #PB_ByteLength) + EndIf + + Case #BakaShrot_Der_PrintableString, #BakaShrot_Der_Ia5String + For i = 0 To Size - 1 + c = PeekA(*C + i) + If c = 0 Or c > 127 + ProcedureReturn #False + EndIf + Next + If Size > 0 + Text = PeekS(*C, Size, #PB_Ascii) + EndIf + + Case #BakaShrot_Der_T61String + For i = 0 To Size - 1 + c = PeekA(*C + i) + If c = 0 + ProcedureReturn #False + EndIf + Text + Chr(c) + Next + + Case #BakaShrot_Der_BmpString + If Size % 2 + ProcedureReturn #False + EndIf + For i = 0 To Size - 2 Step 2 + c = (PeekA(*C + i) << 8) | PeekA(*C + i + 1) + If c = 0 + ProcedureReturn #False + EndIf + Text + Chr(c) + Next + + Default + ProcedureReturn #False + EndSelect + + *Text\s = Text + ProcedureReturn #True +EndProcedure + + +; #True if Text may be a PrintableString: A-Z a-z 0-9 space ' ( ) + , - . / : = ? +Procedure.i BakaShrot_Der_IsPrintable(Text.s) + Protected i.i, c.i + + For i = 1 To Len(Text) + c = Asc(Mid(Text, i, 1)) + If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or FindString(" '()+,-./:=?", Chr(c))) + ProcedureReturn #False + EndIf + Next + ProcedureReturn #True +EndProcedure + + +;- Writing + +Procedure BakaShrot_Der_InitWriter(*Writer.BakaShrot_DerWriter) + *Writer\Buffer = 0 + *Writer\Capacity = 0 + *Writer\Size = 0 + *Writer\Depth = 0 + *Writer\Failed = #False +EndProcedure + + +; Frees what *Writer wrote, for when it's abandoned (BakaShrot_Der_Finish() +; does it otherwise). Zeroed first: it may have held a private key. +Procedure BakaShrot_Der_FreeWriter(*Writer.BakaShrot_DerWriter) + If *Writer\Buffer + FillMemory(*Writer\Buffer, *Writer\Capacity, 0) + FreeMemory(*Writer\Buffer) + EndIf + BakaShrot_Der_InitWriter(*Writer) + *Writer\Failed = #True +EndProcedure + + +; Room for Count more bytes. #False, and the writer fails, without memory or +; past #BakaShrot_Der_MaxSize. +Procedure.i BakaShrot_Der_Reserve(*Writer.BakaShrot_DerWriter, Count.i) + Protected Capacity.i, *Buffer + + If *Writer\Failed + ProcedureReturn #False + EndIf + If Count < 0 Or *Writer\Size + Count > #BakaShrot_Der_MaxSize + 64 + *Writer\Failed = #True + ProcedureReturn #False + EndIf + If *Writer\Size + Count <= *Writer\Capacity + ProcedureReturn #True + EndIf + + Capacity = *Writer\Capacity * 2 + If Capacity < 256 + Capacity = 256 + EndIf + While Capacity < *Writer\Size + Count + Capacity = Capacity * 2 + Wend + If *Writer\Buffer + *Buffer = ReAllocateMemory(*Writer\Buffer, Capacity) + Else + *Buffer = AllocateMemory(Capacity) + EndIf + If Not *Buffer + *Writer\Failed = #True + ProcedureReturn #False + EndIf + *Writer\Buffer = *Buffer + *Writer\Capacity = Capacity + ProcedureReturn #True +EndProcedure + + +; The size of the header (tag and length) of Length bytes of contents. +Procedure.i BakaShrot_Der_HeaderSize(Length.i) + If Length < $80 + ProcedureReturn 2 + ElseIf Length <= $FF + ProcedureReturn 3 + ElseIf Length <= $FFFF + ProcedureReturn 4 + ElseIf Length <= $FFFFFF + ProcedureReturn 5 + EndIf + ProcedureReturn 6 +EndProcedure + + +; Writes the header of Tag with Length bytes of contents at *P. +Procedure BakaShrot_Der_PokeHeader(*P, Tag.i, Length.i) + Protected Count.i = BakaShrot_Der_HeaderSize(Length) - 2, i.i + + PokeA(*P, Tag) + If Count = 0 + PokeA(*P + 1, Length) + Else + PokeA(*P + 1, $80 | Count) + For i = 0 To Count - 1 + PokeA(*P + 2 + i, (Length >> ((Count - 1 - i) * 8)) & $FF) + Next + EndIf +EndProcedure + + +; Writes an element: Tag, and Size bytes of contents from *Content. +Procedure.i BakaShrot_Der_WriteElement(*Writer.BakaShrot_DerWriter, Tag.i, *Content, Size.i) + Protected HeaderSize.i = BakaShrot_Der_HeaderSize(Size) + + If Size < 0 Or (Size > 0 And Not *Content) Or Not BakaShrot_Der_Reserve(*Writer, HeaderSize + Size) + *Writer\Failed = #True + ProcedureReturn #False + EndIf + BakaShrot_Der_PokeHeader(*Writer\Buffer + *Writer\Size, Tag, Size) + If Size > 0 + CopyMemory(*Content, *Writer\Buffer + *Writer\Size + HeaderSize, Size) + EndIf + *Writer\Size + HeaderSize + Size + ProcedureReturn #True +EndProcedure + + +; Writes Size bytes of DER as they are (an element encoded elsewhere). +Procedure.i BakaShrot_Der_WriteRaw(*Writer.BakaShrot_DerWriter, *Data, Size.i) + If Size < 1 Or Not *Data Or Not BakaShrot_Der_Reserve(*Writer, Size) + *Writer\Failed = #True + ProcedureReturn #False + EndIf + CopyMemory(*Data, *Writer\Buffer + *Writer\Size, Size) + *Writer\Size + Size + ProcedureReturn #True +EndProcedure + + +; Begins a constructed element with Tag: what's written until its +; BakaShrot_Der_End() is its contents. +Procedure.i BakaShrot_Der_Begin(*Writer.BakaShrot_DerWriter, Tag.i) + If *Writer\Failed Or *Writer\Depth >= #BakaShrot_Der_MaxDepth + *Writer\Failed = #True + ProcedureReturn #False + EndIf + *Writer\Starts[*Writer\Depth] = *Writer\Size + *Writer\Tags[*Writer\Depth] = Tag + *Writer\Depth + 1 + ProcedureReturn #True +EndProcedure + + +; Ends the element begun last: moves its contents to fit its header before. +Procedure.i BakaShrot_Der_End(*Writer.BakaShrot_DerWriter) + Protected Start.i, Length.i, HeaderSize.i + + If *Writer\Failed Or *Writer\Depth = 0 + *Writer\Failed = #True + ProcedureReturn #False + EndIf + *Writer\Depth - 1 + Start = *Writer\Starts[*Writer\Depth] + Length = *Writer\Size - Start + HeaderSize = BakaShrot_Der_HeaderSize(Length) + If Not BakaShrot_Der_Reserve(*Writer, HeaderSize) + ProcedureReturn #False + EndIf + If Length > 0 + MoveMemory(*Writer\Buffer + Start, *Writer\Buffer + Start + HeaderSize, Length) + EndIf + BakaShrot_Der_PokeHeader(*Writer\Buffer + Start, *Writer\Tags[*Writer\Depth], Length) + *Writer\Size + HeaderSize + ProcedureReturn #True +EndProcedure + + +; What *Writer wrote, in a new buffer (free it with FreeMemory), its size in +; *OutSize\i. 0 if a write failed or an element wasn't ended. +; The writer is freed either way. +Procedure.i BakaShrot_Der_Finish(*Writer.BakaShrot_DerWriter, *OutSize.Integer) + Protected *Result = 0 + + If Not *Writer\Failed And *Writer\Depth = 0 And *Writer\Size > 0 + *Result = AllocateMemory(*Writer\Size) + If *Result + CopyMemory(*Writer\Buffer, *Result, *Writer\Size) + *OutSize\i = *Writer\Size + EndIf + EndIf + BakaShrot_Der_FreeWriter(*Writer) + ProcedureReturn *Result +EndProcedure + + +; An INTEGER, in its shortest form. +Procedure.i BakaShrot_Der_WriteInteger(*Writer.BakaShrot_DerWriter, Value.q) + Protected Dim Bytes.a(7) + Protected i.i, Start.i + + For i = 0 To 7 + Bytes(i) = (Value >> ((7 - i) * 8)) & $FF + Next + ; Drops the leading bytes that only repeat the sign. + While Start < 7 And ((Bytes(Start) = $00 And Bytes(Start + 1) < $80) Or (Bytes(Start) = $FF And Bytes(Start + 1) >= $80)) + Start + 1 + Wend + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Integer, @Bytes(Start), 8 - Start) +EndProcedure + + +; An INTEGER of Size unsigned big-endian bytes at *Bytes, any size (a +; serial number): leading zeros dropped, a zero added if the first bit is set. +Procedure.i BakaShrot_Der_WriteUnsigned(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) + Protected *Content, Start.i, Length.i, Result.i + + While Start < Size And PeekA(*Bytes + Start) = 0 + Start + 1 + Wend + *Content = AllocateMemory(Size - Start + 1) + If Not *Content + *Writer\Failed = #True + ProcedureReturn #False + EndIf + If Start = Size + Length = 1 + ElseIf PeekA(*Bytes + Start) >= $80 + CopyMemory(*Bytes + Start, *Content + 1, Size - Start) + Length = Size - Start + 1 + Else + CopyMemory(*Bytes + Start, *Content, Size - Start) + Length = Size - Start + EndIf + Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Integer, *Content, Length) + FreeMemory(*Content) + ProcedureReturn Result +EndProcedure + + +Procedure.i BakaShrot_Der_WriteBoolean(*Writer.BakaShrot_DerWriter, Value.i) + Protected Byte.a = $00 + + If Value + Byte = $FF + EndIf + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Boolean, @Byte, 1) +EndProcedure + + +Procedure.i BakaShrot_Der_WriteNull(*Writer.BakaShrot_DerWriter) + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Null, 0, 0) +EndProcedure + + +; An OBJECT IDENTIFIER from its dotted text. Fails if it isn't valid. +Procedure.i BakaShrot_Der_WriteOid(*Writer.BakaShrot_DerWriter, Oid.s) + Protected *Buffer, Size.i, Result.i + + *Buffer = AllocateMemory((CountString(Oid, ".") + 1) * #BakaShrot_Der_MaxArcBytes) + If Not *Buffer + *Writer\Failed = #True + ProcedureReturn #False + EndIf + Size = BakaShrot_Der_EncodeOid(Oid, *Buffer, MemorySize(*Buffer)) + If Size > 0 + Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Oid, *Buffer, Size) + Else + *Writer\Failed = #True + EndIf + FreeMemory(*Buffer) + ProcedureReturn Result +EndProcedure + + +Procedure.i BakaShrot_Der_WriteOctetString(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_OctetString, *Bytes, Size) +EndProcedure + + +; A BIT STRING of Size whole bytes (a key, a signature). +Procedure.i BakaShrot_Der_WriteBitStringBytes(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) + Protected *Content, Result.i + + *Content = AllocateMemory(Size + 1) + If Not *Content + *Writer\Failed = #True + ProcedureReturn #False + EndIf + If Size > 0 + CopyMemory(*Bytes, *Content + 1, Size) + EndIf + Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, *Content, Size + 1) + FreeMemory(*Content) + ProcedureReturn Result +EndProcedure + + +; A BIT STRING of named bits from flags (BakaShrot_Der_GetBitFlags()), up +; to 32 bits, without trailing zero bits as DER wants. +Procedure.i BakaShrot_Der_WriteBitFlags(*Writer.BakaShrot_DerWriter, Flags.i) + Protected Dim Content.a(4) + Protected Highest.i = -1, Bit.i, Count.i + + Flags = Flags & $FFFFFFFF + For Bit = 0 To 31 + If Flags & (1 << Bit) + Highest = Bit + Content(1 + Bit / 8) = Content(1 + Bit / 8) | ($80 >> (Bit % 8)) + EndIf + Next + If Highest < 0 + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, @Content(0), 1) + EndIf + Count = Highest / 8 + 1 + Content(0) = 7 - (Highest % 8) + ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, @Content(0), Count + 1) +EndProcedure + + +; A string of type Tag: #BakaShrot_Der_Utf8String, or +; #BakaShrot_Der_PrintableString / #BakaShrot_Der_Ia5String (fails if Text +; doesn't fit them). Fails on a NUL. +Procedure.i BakaShrot_Der_WriteText(*Writer.BakaShrot_DerWriter, Tag.i, Text.s) + Protected *Buffer, Size.i, Result.i, i.i + + If FindString(Text, Chr(0)) + *Writer\Failed = #True + ProcedureReturn #False + EndIf + Select Tag + Case #BakaShrot_Der_Utf8String + Size = StringByteLength(Text, #PB_UTF8) + *Buffer = AllocateMemory(Size + 1) + If *Buffer + PokeS(*Buffer, Text, -1, #PB_UTF8) + EndIf + + Case #BakaShrot_Der_PrintableString, #BakaShrot_Der_Ia5String + For i = 1 To Len(Text) + If Asc(Mid(Text, i, 1)) > 127 + *Writer\Failed = #True + EndIf + Next + If Tag = #BakaShrot_Der_PrintableString And Not BakaShrot_Der_IsPrintable(Text) + *Writer\Failed = #True + EndIf + Size = Len(Text) + *Buffer = AllocateMemory(Size + 1) + If *Buffer + PokeS(*Buffer, Text, -1, #PB_Ascii) + EndIf + + Default + *Writer\Failed = #True + EndSelect + + If *Buffer And Not *Writer\Failed + Result = BakaShrot_Der_WriteElement(*Writer, Tag, *Buffer, Size) + Else + *Writer\Failed = #True + EndIf + If *Buffer + FreeMemory(*Buffer) + EndIf + ProcedureReturn Result +EndProcedure + + +; A time, Seconds since 1970 UTC: a UTCTime from 1950 to 2049, a +; GeneralizedTime otherwise (RFC 5280), years 0000 to 9999. +Procedure.i BakaShrot_Der_WriteTime(*Writer.BakaShrot_DerWriter, Seconds.q) + Protected Days.q, Rest.q, Year.q, Month.q, Day.q, Text.s, Tag.i, *Buffer, Result.i + + Days = Seconds / 86400 + Rest = Seconds % 86400 + If Rest < 0 + Days - 1 + Rest + 86400 + EndIf + BakaShrot_Der_CivilFromDays(Days, @Year, @Month, @Day) + If Year < 0 Or Year > 9999 + *Writer\Failed = #True + ProcedureReturn #False + EndIf + + Text = RSet(Str(Month), 2, "0") + RSet(Str(Day), 2, "0") + RSet(Str(Rest / 3600), 2, "0") + RSet(Str((Rest / 60) % 60), 2, "0") + RSet(Str(Rest % 60), 2, "0") + "Z" + If Year >= 1950 And Year <= 2049 + Tag = #BakaShrot_Der_UtcTime + Text = RSet(Str(Year % 100), 2, "0") + Text + Else + Tag = #BakaShrot_Der_GeneralizedTime + Text = RSet(Str(Year), 4, "0") + Text + EndIf + + *Buffer = AllocateMemory(Len(Text) + 1) + If Not *Buffer + *Writer\Failed = #True + ProcedureReturn #False + EndIf + PokeS(*Buffer, Text, -1, #PB_Ascii) + Result = BakaShrot_Der_WriteElement(*Writer, Tag, *Buffer, Len(Text)) + FreeMemory(*Buffer) + ProcedureReturn Result +EndProcedure diff --git a/Commons/Cryptography/Libsodium.pbi b/OldSource/Commons/Cryptography/Libsodium.pbi similarity index 89% rename from Commons/Cryptography/Libsodium.pbi rename to OldSource/Commons/Cryptography/Libsodium.pbi index f7913ff..5d2ba03 100644 --- a/Commons/Cryptography/Libsodium.pbi +++ b/OldSource/Commons/Cryptography/Libsodium.pbi @@ -160,8 +160,38 @@ CompilerEndIf 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, diff --git a/Commons/Cryptography/Session.pbi b/OldSource/Commons/Cryptography/Session.pbi similarity index 100% rename from Commons/Cryptography/Session.pbi rename to OldSource/Commons/Cryptography/Session.pbi diff --git a/OldSource/Commons/Cryptography/X509.pbi b/OldSource/Commons/Cryptography/X509.pbi new file mode 100644 index 0000000..f509c06 --- /dev/null +++ b/OldSource/Commons/Cryptography/X509.pbi @@ -0,0 +1,1712 @@ +;{- Code Header +; ==- Basic Info -================================ +; Name: X509.pbi +; Version: 0.0.1 +; Author: Herwin Bozet (NibblePoker) +; +; ==- Compatibility -============================= +; Tested compiler versions: +; * PureBasic 5.73 LTS (Windows x64) +; * PureBasic 6.40 C Backend (Windows x64) +; +; ==- Links -===================================== +; GitHub: https://github.com/aziascreations/BakaShrot +;} + +; ============================================================================ +; BakaShrot X.509 certificates +; +; Reading, issuing and checking X.509 v3 certificates (RFC 5280) with +; Ed25519 keys (RFC 8410), the same identity keys as the rest of BakaShrot. +; The same code on Windows and Linux: DER is read and written by Der.pbi, +; every bit of cryptography is libsodium's (Libsodium.pbi): signatures, +; SHA-256, random serial numbers, Base64 and hex. +; Not the OS's certificate APIs: Windows' CryptoAPI can't check Ed25519 +; certificates, and OpenSSL would be another library to ship. The +; certificates are standard all the same: OpenSSL reads and checks them, +; and they're checked against it (Tests/X509-Test.ps1). +; +; Reading: BakaShrot_X509_Parse() (DER), _ParsePem(), _Load() (a file, PEM +; or DER) give a BakaShrot_X509Certificate, freed with BakaShrot_X509_Free(). +; Any certificate is read (RSA, ECDSA...), its fields and extensions are +; there, but only Ed25519 ones can be checked or issue others. +; +; Issuing: fill a BakaShrot_X509Template (subject, validity, the subject's +; public key, CA or not, key usage, custom extensions), then +; BakaShrot_X509_Issue() with the issuer's certificate and private key, or +; none for a self-signed one. BakaShrot_X509_ClearTemplate() once done. +; +; Checking: BakaShrot_X509_CheckIssuedBy() for one link, _VerifyChain() +; from a leaf up to a trusted root, _CheckSignature(), _CheckValidity(). +; Each returns a #BakaShrot_X509_* code, #BakaShrot_X509_Ok (0) if it +; holds; BakaShrot_X509_ErrorName() names it. +; +; Custom fields are extensions under #BakaShrot_Oid_Extensions: +; BakaShrot_X509_AddTextExtension() / _AddIntegerExtension() / +; _AddExtension() (any DER) on a template, BakaShrot_X509_GetExtensionText() +; / _GetExtensionInteger() / _FindExtension() on a certificate. Critical +; ones a reader doesn't know make the certificate refused, unless the +; caller says it handles them (the Handled argument of the checks). +; +; Times are seconds since 1970-01-01 00:00:00 UTC (BakaShrot_X509_Now()). +; Hex is lowercase, without separators. +; +; Threads: no globals. A parsed certificate is only read once parsed, its +; names and extensions are arrays, not lists: any number of threads may +; read and check one at once (the server's CA, say). +; ============================================================================ + +XIncludeFile "Libsodium.pbi" +XIncludeFile "Der.pbi" + + +;- OIDs + +#BakaShrot_Oid_Ed25519 = "1.3.101.112" + +; Name attributes. BakaShrot_X509_NameAdd() also takes their short names. +#BakaShrot_Oid_CommonName = "2.5.4.3" +#BakaShrot_Oid_SerialNumber = "2.5.4.5" +#BakaShrot_Oid_Country = "2.5.4.6" +#BakaShrot_Oid_Locality = "2.5.4.7" +#BakaShrot_Oid_State = "2.5.4.8" +#BakaShrot_Oid_Organization = "2.5.4.10" +#BakaShrot_Oid_OrganizationalUnit = "2.5.4.11" +#BakaShrot_Oid_EmailAddress = "1.2.840.113549.1.9.1" +#BakaShrot_Oid_DomainComponent = "0.9.2342.19200300.100.1.25" +#BakaShrot_Oid_UserId = "0.9.2342.19200300.100.1.1" + +; The extensions this file reads and writes itself. +#BakaShrot_Oid_SubjectKeyId = "2.5.29.14" +#BakaShrot_Oid_KeyUsage = "2.5.29.15" +#BakaShrot_Oid_BasicConstraints = "2.5.29.19" +#BakaShrot_Oid_AuthorityKeyId = "2.5.29.35" + +; BakaShrot's own OID arc: a UUID OID (2.25, ITU-T X.667 / RFC 4122), which +; needs no registration. Made 2026-11-13 from the random UUID +; ae8e863a-dae2-47b2-a285-751106c98f65. +#BakaShrot_Oid_Arc = "2.25.232025699926348910519219903487382490981" + +; BakaShrot's custom certificate extensions: #BakaShrot_Oid_Extensions + +; ".", numbered as they're defined, a number never reused. None yet. +; (Tests/X509Test.pb uses .9000 and up.) +#BakaShrot_Oid_Extensions = #BakaShrot_Oid_Arc + ".1" + + +;- Key usage + +; KeyUsage bits as flags (bit n of the extension's BIT STRING is 1 << n). +#BakaShrot_X509_KeyUsage_DigitalSignature = 1 << 0 +#BakaShrot_X509_KeyUsage_NonRepudiation = 1 << 1 +#BakaShrot_X509_KeyUsage_KeyEncipherment = 1 << 2 +#BakaShrot_X509_KeyUsage_DataEncipherment = 1 << 3 +#BakaShrot_X509_KeyUsage_KeyAgreement = 1 << 4 +#BakaShrot_X509_KeyUsage_KeyCertSign = 1 << 5 +#BakaShrot_X509_KeyUsage_CrlSign = 1 << 6 +#BakaShrot_X509_KeyUsage_EncipherOnly = 1 << 7 +#BakaShrot_X509_KeyUsage_DecipherOnly = 1 << 8 + + +;- Results + +Enumeration BakaShrot_X509Results + #BakaShrot_X509_Ok = 0 + ; Not a DER X.509 certificate (or PEM of one), or broken somewhere. + #BakaShrot_X509_Error_Malformed = 1 + ; Not Ed25519: it can be read, not checked nor used to issue. + #BakaShrot_X509_Error_Unsupported = 2 + ; Its signature isn't its issuer's. + #BakaShrot_X509_Error_BadSignature = 3 + ; Checked before its NotBefore, or after its NotAfter. + #BakaShrot_X509_Error_NotYetValid = 4 + #BakaShrot_X509_Error_Expired = 5 + ; It names another issuer (name, or key id) than the one it's checked with. + #BakaShrot_X509_Error_IssuerMismatch = 6 + ; Its issuer isn't a CA (BasicConstraints), or may not sign certificates (KeyUsage). + #BakaShrot_X509_Error_NotCa = 7 + ; More CAs under a CA than its PathLength allows. + #BakaShrot_X509_Error_PathTooLong = 8 + ; A critical extension nobody handles. + #BakaShrot_X509_Error_UnknownCritical = 9 + ; Issuing: the private key isn't the issuer's (or, self-signed, the subject's). + #BakaShrot_X509_Error_KeyMismatch = 10 + ; A missing or invalid argument, a template that can't be issued. + #BakaShrot_X509_Error_InvalidArgument = 11 + ; Out of memory, a file that can't be read. + #BakaShrot_X509_Error_Internal = 12 +EndEnumeration + + +Procedure.s BakaShrot_X509_ErrorName(Code.i) + Select Code + Case #BakaShrot_X509_Ok : ProcedureReturn "Ok" + Case #BakaShrot_X509_Error_Malformed : ProcedureReturn "Malformed" + Case #BakaShrot_X509_Error_Unsupported : ProcedureReturn "Unsupported" + Case #BakaShrot_X509_Error_BadSignature : ProcedureReturn "BadSignature" + Case #BakaShrot_X509_Error_NotYetValid : ProcedureReturn "NotYetValid" + Case #BakaShrot_X509_Error_Expired : ProcedureReturn "Expired" + Case #BakaShrot_X509_Error_IssuerMismatch : ProcedureReturn "IssuerMismatch" + Case #BakaShrot_X509_Error_NotCa : ProcedureReturn "NotCa" + Case #BakaShrot_X509_Error_PathTooLong : ProcedureReturn "PathTooLong" + Case #BakaShrot_X509_Error_UnknownCritical : ProcedureReturn "UnknownCritical" + Case #BakaShrot_X509_Error_KeyMismatch : ProcedureReturn "KeyMismatch" + Case #BakaShrot_X509_Error_InvalidArgument : ProcedureReturn "InvalidArgument" + Case #BakaShrot_X509_Error_Internal : ProcedureReturn "Internal" + EndSelect + ProcedureReturn "Unknown" + Str(Code) +EndProcedure + + +;- Structures + +; Key ids are the first 20 bytes of the SHA-256 of the public key (RFC 7093). +#BakaShrot_X509_KeyIdSize = 20 + +; Random serial numbers, when the template has none. +#BakaShrot_X509_SerialSize = 16 + +; The longest serial number taken (RFC 5280 allows 20 bytes, some write 21). +#BakaShrot_X509_MaxSerialSize = 32 + + +Structure BakaShrot_X509NameAttribute + ; Its type's OID ("2.5.4.3" for CN). + Oid.s + Value.s + ; Read: its DER string type (#BakaShrot_Der_Utf8String...). Issuing: 0 + ; picks the usual one (PrintableString for C, IA5String for emailAddress + ; and DC, UTF8String otherwise). + StringTag.i + ; Read: its RDN's index, attributes of a multi-valued RDN share it. + ; Issuing: each attribute is its own RDN, this is ignored. + Rdn.i +EndStructure + +; A distinguished name, its attributes in the certificate's order. +Structure BakaShrot_X509Name + Count.i + Array Attributes.BakaShrot_X509NameAttribute(0) +EndStructure + + +Structure BakaShrot_X509Extension + Oid.s + Critical.i + ; extnValue's contents: the extension's own DER. Owned by the + ; certificate or template it's in. + *Value + ValueSize.i +EndStructure + + +Structure BakaShrot_X509Certificate + ; The whole certificate, DER, owned. The offsets point into it. + *Der + DerSize.i + ; What the signature covers (tbsCertificate). + TbsOffset.i + TbsSize.i + ; The issuer's and subject's names as encoded: issuers are matched on these. + IssuerOffset.i + IssuerSize.i + SubjectOffset.i + SubjectSize.i + + ; 1 to 3. + Version.i + ; Hex, without the sign byte. + Serial.s + SignatureAlgorithm.s + Issuer.BakaShrot_X509Name + Subject.BakaShrot_X509Name + NotBefore.q + NotAfter.q + KeyAlgorithm.s + + ; Ed25519 only. + HasEd25519Key.i + PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] + HasEd25519Signature.i + Signature.a[#BakaShrot_Ed25519_SignatureSize] + + ; Every extension, in order, the known ones too. + ExtensionCount.i + Array Extensions.BakaShrot_X509Extension(0) + + ; From BasicConstraints. PathLength -1 when there's none. + HasBasicConstraints.i + IsCa.i + PathLength.i + ; From KeyUsage, #BakaShrot_X509_KeyUsage_* flags. + HasKeyUsage.i + KeyUsage.i + ; Hex, "" when absent. + SubjectKeyId.s + AuthorityKeyId.s +EndStructure + + +; What BakaShrot_X509_Issue() makes a certificate of. Set PathLength -1 +; (no limit) or call BakaShrot_X509_InitTemplate() first, and +; BakaShrot_X509_ClearTemplate() once done (it holds the extensions' values). +Structure BakaShrot_X509Template + ; Hex; "" for #BakaShrot_X509_SerialSize random bytes. + Serial.s + Subject.BakaShrot_X509Name + NotBefore.q + NotAfter.q + ; The subject's Ed25519 public key. + PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] + ; BasicConstraints, always written (critical). PathLength: CAs only, the + ; most CAs under this one, -1 for no limit. + IsCa.i + PathLength.i + ; KeyUsage (critical), #BakaShrot_X509_KeyUsage_* flags. 0: none written. + KeyUsage.i + ; Added with BakaShrot_X509_Add*Extension(), written after the standard ones. + ExtensionCount.i + Array Extensions.BakaShrot_X509Extension(0) +EndStructure + + +;- Helpers + +; Now, in seconds since 1970 UTC, for the checks. +CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + ImportC "" + BakaShrot_X509_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday" + EndImport +CompilerEndIf + +Procedure.q BakaShrot_X509_Now() + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + ; 100 ns intervals since 1601-01-01 UTC. + Protected FileTime.q + GetSystemTimeAsFileTime_(@FileTime) + ProcedureReturn (FileTime - 116444736000000000) / 10000000 + CompilerElse + Protected Dim TimeVal.q(1) + BakaShrot_X509_GetTimeOfDay(@TimeVal(0), 0) + ProcedureReturn TimeVal(0) + CompilerEndIf +EndProcedure + + +; Size bytes at *Data in lowercase hex. +Procedure.s BakaShrot_X509_Hex(*Data, Size.i) + Protected *Text, Text.s + + If Size < 1 + ProcedureReturn "" + EndIf + *Text = AllocateMemory(Size * 2 + 1) + If Not *Text + ProcedureReturn "" + EndIf + sodium_bin2hex(*Text, Size * 2 + 1, *Data, Size) + Text = PeekS(*Text, Size * 2, #PB_Ascii) + FreeMemory(*Text) + ProcedureReturn Text +EndProcedure + + +; Text as a new buffer of ASCII, its size (without the terminator) in +; *Size\i. 0 if it isn't ASCII. Free it with FreeMemory. +Procedure.i BakaShrot_X509_Ascii(Text.s, *Size.Integer) + Protected *Buffer, i.i + + For i = 1 To Len(Text) + If Asc(Mid(Text, i, 1)) > 127 + ProcedureReturn 0 + EndIf + Next + *Buffer = AllocateMemory(Len(Text) + 1) + If *Buffer + PokeS(*Buffer, Text, -1, #PB_Ascii) + *Size\i = Len(Text) + EndIf + ProcedureReturn *Buffer +EndProcedure + + +; Hex (any case) into *Out, at most MaxSize bytes. Returns how many, -1 if +; it isn't hex or doesn't fit. +Procedure.i BakaShrot_X509_FromHex(Hex.s, *Out, MaxSize.i) + Protected *Text, TextSize.Integer, Size.Integer, Result.i = -1 + + *Text = BakaShrot_X509_Ascii(Hex, @TextSize) + If *Text + If sodium_hex2bin(*Out, MaxSize, *Text, TextSize\i, 0, @Size, 0) = 0 + Result = Size\i + EndIf + FreeMemory(*Text) + EndIf + ProcedureReturn Result +EndProcedure + + +; The key id of an Ed25519 public key into *Out (#BakaShrot_X509_KeyIdSize +; bytes): the first 20 bytes of its SHA-256 (RFC 7093, method 1). +Procedure BakaShrot_X509_KeyId(*PublicKey, *Out) + Protected Dim Hash.a(#BakaShrot_Sha256_HashSize - 1) + + crypto_hash_sha256(@Hash(0), *PublicKey, #BakaShrot_Ed25519_PublicKeySize) + CopyMemory(@Hash(0), *Out, #BakaShrot_X509_KeyIdSize) +EndProcedure + + +;- Names + +; The OID of an attribute type: a short name (CN, O, OU, C, L, ST, +; serialNumber, emailAddress, DC, UID, any case) or an OID as is. "" if +; neither. +Procedure.s BakaShrot_X509_NameTypeOid(Type.s) + Select LCase(Type) + Case "cn" : ProcedureReturn #BakaShrot_Oid_CommonName + Case "serialnumber" : ProcedureReturn #BakaShrot_Oid_SerialNumber + Case "c" : ProcedureReturn #BakaShrot_Oid_Country + Case "l" : ProcedureReturn #BakaShrot_Oid_Locality + Case "st" : ProcedureReturn #BakaShrot_Oid_State + Case "o" : ProcedureReturn #BakaShrot_Oid_Organization + Case "ou" : ProcedureReturn #BakaShrot_Oid_OrganizationalUnit + Case "emailaddress" : ProcedureReturn #BakaShrot_Oid_EmailAddress + Case "dc" : ProcedureReturn #BakaShrot_Oid_DomainComponent + Case "uid" : ProcedureReturn #BakaShrot_Oid_UserId + EndSelect + If BakaShrot_Der_IsValidOid(Type) + ProcedureReturn Type + EndIf + ProcedureReturn "" +EndProcedure + + +; The short name of an attribute type's OID, the OID itself if it has none. +Procedure.s BakaShrot_X509_NameTypeShort(Oid.s) + Select Oid + Case #BakaShrot_Oid_CommonName : ProcedureReturn "CN" + Case #BakaShrot_Oid_SerialNumber : ProcedureReturn "serialNumber" + Case #BakaShrot_Oid_Country : ProcedureReturn "C" + Case #BakaShrot_Oid_Locality : ProcedureReturn "L" + Case #BakaShrot_Oid_State : ProcedureReturn "ST" + Case #BakaShrot_Oid_Organization : ProcedureReturn "O" + Case #BakaShrot_Oid_OrganizationalUnit : ProcedureReturn "OU" + Case #BakaShrot_Oid_EmailAddress : ProcedureReturn "emailAddress" + Case #BakaShrot_Oid_DomainComponent : ProcedureReturn "DC" + Case #BakaShrot_Oid_UserId : ProcedureReturn "UID" + EndSelect + ProcedureReturn Oid +EndProcedure + + +; Adds an attribute at the end of *Name. Type: a short name or an OID, see +; BakaShrot_X509_NameTypeOid(). StringTag: see BakaShrot_X509NameAttribute. +; Returns #False if Type is neither. +Procedure.i BakaShrot_X509_NameAdd(*Name.BakaShrot_X509Name, Type.s, Value.s, StringTag.i = 0, Rdn.i = -1) + Protected Oid.s = BakaShrot_X509_NameTypeOid(Type) + + If Oid = "" + ProcedureReturn #False + EndIf + If *Name\Count > ArraySize(*Name\Attributes()) + ReDim *Name\Attributes(*Name\Count * 2 + 3) + EndIf + If Rdn < 0 + Rdn = *Name\Count + EndIf + *Name\Attributes(*Name\Count)\Oid = Oid + *Name\Attributes(*Name\Count)\Value = Value + *Name\Attributes(*Name\Count)\StringTag = StringTag + *Name\Attributes(*Name\Count)\Rdn = Rdn + *Name\Count + 1 + ProcedureReturn #True +EndProcedure + + +; The first value of the attribute Type (a short name or an OID) in *Name, +; "" if it has none. +Procedure.s BakaShrot_X509_NameGet(*Name.BakaShrot_X509Name, Type.s) + Protected Oid.s = BakaShrot_X509_NameTypeOid(Type), i.i + + For i = 0 To *Name\Count - 1 + If *Name\Attributes(i)\Oid = Oid + ProcedureReturn *Name\Attributes(i)\Value + EndIf + Next + ProcedureReturn "" +EndProcedure + + +; *Name as "CN=demo, O=BakaShrot", in the certificate's order, the +; attributes of a multi-valued RDN joined with "+". For people: values +; aren't escaped. +Procedure.s BakaShrot_X509_NameToString(*Name.BakaShrot_X509Name) + Protected i.i, Text.s + + For i = 0 To *Name\Count - 1 + If i > 0 + If *Name\Attributes(i)\Rdn = *Name\Attributes(i - 1)\Rdn + Text + "+" + Else + Text + ", " + EndIf + EndIf + Text + BakaShrot_X509_NameTypeShort(*Name\Attributes(i)\Oid) + "=" + *Name\Attributes(i)\Value + Next + ProcedureReturn Text +EndProcedure + + +;- Reading + +; Frees a certificate from BakaShrot_X509_Parse() and the like. +Procedure BakaShrot_X509_Free(*Cert.BakaShrot_X509Certificate) + Protected i.i + + If Not *Cert + ProcedureReturn + EndIf + For i = 0 To *Cert\ExtensionCount - 1 + If *Cert\Extensions(i)\Value + FreeMemory(*Cert\Extensions(i)\Value) + EndIf + Next + If *Cert\Der + FreeMemory(*Cert\Der) + EndIf + FreeStructure(*Cert) +EndProcedure + + +; An AlgorithmIdentifier: its OID into *Oid\s, and whether it has +; parameters (any) into *HasParameters\i. +Procedure.i BakaShrot_X509_ReadAlgorithm(*Element.BakaShrot_DerElement, *Oid.String, *HasParameters.Integer) + Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement + + BakaShrot_Der_ReaderOf(@Reader, *Element) + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Oid, @Item) + ProcedureReturn #False + EndIf + *Oid\s = BakaShrot_Der_GetOid(@Item) + If *Oid\s = "" + ProcedureReturn #False + EndIf + *HasParameters\i = #False + If Not BakaShrot_Der_AtEnd(@Reader) + *HasParameters\i = #True + If Not BakaShrot_Der_Read(@Reader, @Item) + ProcedureReturn #False + EndIf + EndIf + ProcedureReturn BakaShrot_Der_AtEnd(@Reader) +EndProcedure + + +; A Name: a SEQUENCE of RDNs, each a SET of (type, string) pairs. +Procedure.i BakaShrot_X509_ReadName(*Element.BakaShrot_DerElement, *Name.BakaShrot_X509Name) + Protected Names.BakaShrot_DerReader, Rdns.BakaShrot_DerReader, Pair.BakaShrot_DerReader + Protected RdnSet.BakaShrot_DerElement, Attribute.BakaShrot_DerElement, Item.BakaShrot_DerElement + Protected Rdn.i, Oid.s, Value.String + + BakaShrot_Der_ReaderOf(@Names, *Element) + While Not BakaShrot_Der_AtEnd(@Names) + If Not BakaShrot_Der_Expect(@Names, #BakaShrot_Der_Set, @RdnSet) + ProcedureReturn #False + EndIf + BakaShrot_Der_ReaderOf(@Rdns, @RdnSet) + ; An RDN has one attribute at least. + If BakaShrot_Der_AtEnd(@Rdns) + ProcedureReturn #False + EndIf + While Not BakaShrot_Der_AtEnd(@Rdns) + If Not BakaShrot_Der_Expect(@Rdns, #BakaShrot_Der_Sequence, @Attribute) + ProcedureReturn #False + EndIf + BakaShrot_Der_ReaderOf(@Pair, @Attribute) + If Not BakaShrot_Der_Expect(@Pair, #BakaShrot_Der_Oid, @Item) + ProcedureReturn #False + EndIf + Oid = BakaShrot_Der_GetOid(@Item) + If Oid = "" Or Not BakaShrot_Der_Read(@Pair, @Item) Or Not BakaShrot_Der_AtEnd(@Pair) + ProcedureReturn #False + EndIf + If Not BakaShrot_Der_GetText(@Item, @Value) + ProcedureReturn #False + EndIf + BakaShrot_X509_NameAdd(*Name, Oid, Value\s, Item\Tag, Rdn) + Wend + Rdn + 1 + Wend + ProcedureReturn BakaShrot_Der_AtEnd(@Names) +EndProcedure + + +; The known extension *Extension's fields into *Cert. #False if malformed. +Procedure.i BakaShrot_X509_ReadKnownExtension(*Cert.BakaShrot_X509Certificate, *Extension.BakaShrot_X509Extension) + Protected Reader.BakaShrot_DerReader, Inner.BakaShrot_DerReader + Protected Item.BakaShrot_DerElement, Field.BakaShrot_DerElement, Value.q, Flag.i + + BakaShrot_Der_InitReader(@Reader, *Extension\Value, *Extension\ValueSize) + Select *Extension\Oid + + Case #BakaShrot_Oid_BasicConstraints + ; SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER OPTIONAL } + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Item) + ProcedureReturn #False + EndIf + BakaShrot_Der_ReaderOf(@Inner, @Item) + If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Boolean + If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetBoolean(@Field, @Flag) + ProcedureReturn #False + EndIf + *Cert\IsCa = Flag + EndIf + If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Integer + If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetInteger(@Field, @Value) Or Value < 0 Or Value > 255 + ProcedureReturn #False + EndIf + *Cert\PathLength = Value + EndIf + If Not BakaShrot_Der_AtEnd(@Inner) + ProcedureReturn #False + EndIf + *Cert\HasBasicConstraints = #True + + Case #BakaShrot_Oid_KeyUsage + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_BitString, @Item) Or Not BakaShrot_Der_GetBitFlags(@Item, @Flag) + ProcedureReturn #False + EndIf + *Cert\KeyUsage = Flag + *Cert\HasKeyUsage = #True + + Case #BakaShrot_Oid_SubjectKeyId + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_OctetString, @Item) Or Item\ContentSize < 1 + ProcedureReturn #False + EndIf + *Cert\SubjectKeyId = BakaShrot_X509_Hex(Item\Content, Item\ContentSize) + + Case #BakaShrot_Oid_AuthorityKeyId + ; SEQUENCE { keyIdentifier [0] OPTIONAL, authorityCertIssuer [1] OPTIONAL, authorityCertSerialNumber [2] OPTIONAL } + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Item) + ProcedureReturn #False + EndIf + BakaShrot_Der_ReaderOf(@Inner, @Item) + If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Context | 0 + If Not BakaShrot_Der_Read(@Inner, @Field) Or Field\ContentSize < 1 + ProcedureReturn #False + EndIf + *Cert\AuthorityKeyId = BakaShrot_X509_Hex(Field\Content, Field\ContentSize) + EndIf + If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_ContextConstructed | 1 + BakaShrot_Der_Read(@Inner, @Field) + EndIf + If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Context | 2 + BakaShrot_Der_Read(@Inner, @Field) + EndIf + If Not BakaShrot_Der_AtEnd(@Inner) + ProcedureReturn #False + EndIf + + Default + ProcedureReturn #True + EndSelect + + ProcedureReturn BakaShrot_Der_AtEnd(@Reader) +EndProcedure + + +; Extensions: a SEQUENCE of one or more SEQUENCE { extnID OID, critical +; BOOLEAN DEFAULT FALSE, extnValue OCTET STRING }, each OID once at most. +Procedure.i BakaShrot_X509_ReadExtensions(*Element.BakaShrot_DerElement, *Cert.BakaShrot_X509Certificate) + Protected Items.BakaShrot_DerReader, Fields.BakaShrot_DerReader, Check.BakaShrot_DerReader + Protected Extension.BakaShrot_DerElement, Item.BakaShrot_DerElement + Protected Oid.s, Critical.i, i.i, Index.i + + BakaShrot_Der_ReaderOf(@Items, *Element) + If BakaShrot_Der_AtEnd(@Items) + ProcedureReturn #False + EndIf + While Not BakaShrot_Der_AtEnd(@Items) + If Not BakaShrot_Der_Expect(@Items, #BakaShrot_Der_Sequence, @Extension) + ProcedureReturn #False + EndIf + BakaShrot_Der_ReaderOf(@Fields, @Extension) + If Not BakaShrot_Der_Expect(@Fields, #BakaShrot_Der_Oid, @Item) + ProcedureReturn #False + EndIf + Oid = BakaShrot_Der_GetOid(@Item) + If Oid = "" + ProcedureReturn #False + EndIf + For i = 0 To *Cert\ExtensionCount - 1 + If *Cert\Extensions(i)\Oid = Oid + ProcedureReturn #False + EndIf + Next + Critical = #False + If BakaShrot_Der_PeekTag(@Fields) = #BakaShrot_Der_Boolean + If Not BakaShrot_Der_Read(@Fields, @Item) Or Not BakaShrot_Der_GetBoolean(@Item, @Critical) + ProcedureReturn #False + EndIf + EndIf + If Not BakaShrot_Der_Expect(@Fields, #BakaShrot_Der_OctetString, @Item) Or Not BakaShrot_Der_AtEnd(@Fields) + ProcedureReturn #False + EndIf + ; extnValue holds one DER element. + BakaShrot_Der_ReaderOf(@Check, @Item) + If Not BakaShrot_Der_Read(@Check, @Extension) Or Not BakaShrot_Der_AtEnd(@Check) + ProcedureReturn #False + EndIf + + Index = *Cert\ExtensionCount + If Index > ArraySize(*Cert\Extensions()) + ReDim *Cert\Extensions(Index * 2 + 3) + EndIf + *Cert\Extensions(Index)\Oid = Oid + *Cert\Extensions(Index)\Critical = Critical + *Cert\Extensions(Index)\ValueSize = Item\ContentSize + *Cert\Extensions(Index)\Value = AllocateMemory(Item\ContentSize) + If Not *Cert\Extensions(Index)\Value + ProcedureReturn #False + EndIf + CopyMemory(Item\Content, *Cert\Extensions(Index)\Value, Item\ContentSize) + *Cert\ExtensionCount + 1 + + If Not BakaShrot_X509_ReadKnownExtension(*Cert, @*Cert\Extensions(Index)) + ProcedureReturn #False + EndIf + Wend + ProcedureReturn #True +EndProcedure + + +; Reads a DER certificate, Size bytes at *Der (copied: it may be freed after). +; Returns a new BakaShrot_X509Certificate (free it with BakaShrot_X509_Free()), +; or 0 with *Error\l set (#BakaShrot_X509_Error_Malformed...), if given. +; Any algorithm is read; for Ed25519 the key and signature must be right. +; Nothing may follow the certificate. +Procedure.i BakaShrot_X509_Parse(*Der, Size.i, *Error.Long = 0) + Protected *Cert.BakaShrot_X509Certificate, Code.i = #BakaShrot_X509_Error_Malformed + Protected Top.BakaShrot_DerReader, Outer.BakaShrot_DerReader, Tbs.BakaShrot_DerReader, Inner.BakaShrot_DerReader + Protected CertElement.BakaShrot_DerElement, TbsElement.BakaShrot_DerElement, OuterAlgorithm.BakaShrot_DerElement + Protected SignatureElement.BakaShrot_DerElement, Item.BakaShrot_DerElement, Field.BakaShrot_DerElement + Protected Value.q, Oid.String, HasParameters.i, *Bytes, BytesSize.i + + If Not *Der Or Size < 1 Or Size > #BakaShrot_Der_MaxSize + Code = #BakaShrot_X509_Error_InvalidArgument + Goto ParseFailed + EndIf + *Cert = AllocateStructure(BakaShrot_X509Certificate) + If *Cert + *Cert\Der = AllocateMemory(Size) + EndIf + If Not *Cert Or Not *Cert\Der + Code = #BakaShrot_X509_Error_Internal + Goto ParseFailed + EndIf + CopyMemory(*Der, *Cert\Der, Size) + *Cert\DerSize = Size + *Cert\PathLength = -1 + + ; Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue } + BakaShrot_Der_InitReader(@Top, *Cert\Der, Size) + If Not BakaShrot_Der_Expect(@Top, #BakaShrot_Der_Sequence, @CertElement) Or Not BakaShrot_Der_AtEnd(@Top) + Goto ParseFailed + EndIf + BakaShrot_Der_ReaderOf(@Outer, @CertElement) + If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_Sequence, @TbsElement) + Goto ParseFailed + EndIf + If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_Sequence, @OuterAlgorithm) + Goto ParseFailed + EndIf + If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_BitString, @SignatureElement) Or Not BakaShrot_Der_AtEnd(@Outer) + Goto ParseFailed + EndIf + *Cert\TbsOffset = TbsElement\Start - *Cert\Der + *Cert\TbsSize = TbsElement\Size + + BakaShrot_Der_ReaderOf(@Tbs, @TbsElement) + + ; version [0] EXPLICIT INTEGER DEFAULT v1: v1 is never written. + *Cert\Version = 1 + If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_ContextConstructed | 0 + BakaShrot_Der_Read(@Tbs, @Item) + BakaShrot_Der_ReaderOf(@Inner, @Item) + If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Integer, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) + Goto ParseFailed + EndIf + If Not BakaShrot_Der_GetInteger(@Field, @Value) Or Value < 1 Or Value > 2 + Goto ParseFailed + EndIf + *Cert\Version = Value + 1 + EndIf + + ; serialNumber + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Integer, @Item) Or Not BakaShrot_Der_IsMinimalInteger(@Item) Or Item\ContentSize > #BakaShrot_X509_MaxSerialSize + Goto ParseFailed + EndIf + If Item\ContentSize > 1 And PeekA(Item\Content) = 0 + *Cert\Serial = BakaShrot_X509_Hex(Item\Content + 1, Item\ContentSize - 1) + Else + *Cert\Serial = BakaShrot_X509_Hex(Item\Content, Item\ContentSize) + EndIf + + ; signature: the same AlgorithmIdentifier as the outer one, byte for byte. + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) + Goto ParseFailed + EndIf + If Item\Size <> OuterAlgorithm\Size Or Not CompareMemory(Item\Start, OuterAlgorithm\Start, Item\Size) + Goto ParseFailed + EndIf + If Not BakaShrot_X509_ReadAlgorithm(@Item, @Oid, @HasParameters) + Goto ParseFailed + EndIf + *Cert\SignatureAlgorithm = Oid\s + ; Ed25519 has no parameters (RFC 8410). + If Oid\s = #BakaShrot_Oid_Ed25519 And HasParameters + Goto ParseFailed + EndIf + + ; issuer + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) Or Not BakaShrot_X509_ReadName(@Item, @*Cert\Issuer) + Goto ParseFailed + EndIf + *Cert\IssuerOffset = Item\Start - *Cert\Der + *Cert\IssuerSize = Item\Size + + ; validity + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) + Goto ParseFailed + EndIf + BakaShrot_Der_ReaderOf(@Inner, @Item) + If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetTime(@Field, @*Cert\NotBefore) + Goto ParseFailed + EndIf + If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetTime(@Field, @*Cert\NotAfter) Or Not BakaShrot_Der_AtEnd(@Inner) + Goto ParseFailed + EndIf + + ; subject + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) Or Not BakaShrot_X509_ReadName(@Item, @*Cert\Subject) + Goto ParseFailed + EndIf + *Cert\SubjectOffset = Item\Start - *Cert\Der + *Cert\SubjectSize = Item\Size + + ; subjectPublicKeyInfo ::= SEQUENCE { algorithm, subjectPublicKey BIT STRING } + If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) + Goto ParseFailed + EndIf + BakaShrot_Der_ReaderOf(@Inner, @Item) + If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Sequence, @Field) Or Not BakaShrot_X509_ReadAlgorithm(@Field, @Oid, @HasParameters) + Goto ParseFailed + EndIf + *Cert\KeyAlgorithm = Oid\s + If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_BitString, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) + Goto ParseFailed + EndIf + If Oid\s = #BakaShrot_Oid_Ed25519 + If HasParameters Or Not BakaShrot_Der_GetBitStringBytes(@Field, @*Bytes, @BytesSize) Or BytesSize <> #BakaShrot_Ed25519_PublicKeySize + Goto ParseFailed + EndIf + CopyMemory(*Bytes, @*Cert\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + *Cert\HasEd25519Key = #True + EndIf + + ; issuerUniqueID [1], subjectUniqueID [2]: v2 and v3 only, skipped. + If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_Context | 1 + If *Cert\Version < 2 Or Not BakaShrot_Der_Read(@Tbs, @Item) + Goto ParseFailed + EndIf + EndIf + If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_Context | 2 + If *Cert\Version < 2 Or Not BakaShrot_Der_Read(@Tbs, @Item) + Goto ParseFailed + EndIf + EndIf + + ; extensions [3] EXPLICIT, v3 only. + If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_ContextConstructed | 3 + If *Cert\Version <> 3 + Goto ParseFailed + EndIf + BakaShrot_Der_Read(@Tbs, @Item) + BakaShrot_Der_ReaderOf(@Inner, @Item) + If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Sequence, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) + Goto ParseFailed + EndIf + If Not BakaShrot_X509_ReadExtensions(@Field, *Cert) + Goto ParseFailed + EndIf + EndIf + If Not BakaShrot_Der_AtEnd(@Tbs) + Goto ParseFailed + EndIf + + ; signatureValue + If Not BakaShrot_Der_GetBitStringBytes(@SignatureElement, @*Bytes, @BytesSize) + Goto ParseFailed + EndIf + If *Cert\SignatureAlgorithm = #BakaShrot_Oid_Ed25519 + If BytesSize <> #BakaShrot_Ed25519_SignatureSize + Goto ParseFailed + EndIf + CopyMemory(*Bytes, @*Cert\Signature[0], #BakaShrot_Ed25519_SignatureSize) + *Cert\HasEd25519Signature = #True + EndIf + + If *Error + *Error\l = #BakaShrot_X509_Ok + EndIf + ProcedureReturn *Cert + + ParseFailed: + BakaShrot_X509_Free(*Cert) + If *Error + *Error\l = Code + EndIf + ProcedureReturn 0 +EndProcedure + + +; The index of the extension Oid in *Cert, -1 if it has none. +Procedure.i BakaShrot_X509_FindExtension(*Cert.BakaShrot_X509Certificate, Oid.s) + Protected i.i + + For i = 0 To *Cert\ExtensionCount - 1 + If *Cert\Extensions(i)\Oid = Oid + ProcedureReturn i + EndIf + Next + ProcedureReturn -1 +EndProcedure + + +; The text of the extension Oid, a single DER string (see +; BakaShrot_Der_GetText()), into *Text\s. #False if *Cert has none, or it +; isn't a string. +Procedure.i BakaShrot_X509_GetExtensionText(*Cert.BakaShrot_X509Certificate, Oid.s, *Text.String) + Protected Index.i = BakaShrot_X509_FindExtension(*Cert, Oid) + Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement + + If Index < 0 + ProcedureReturn #False + EndIf + BakaShrot_Der_InitReader(@Reader, *Cert\Extensions(Index)\Value, *Cert\Extensions(Index)\ValueSize) + If Not BakaShrot_Der_Read(@Reader, @Item) Or Not BakaShrot_Der_AtEnd(@Reader) + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_Der_GetText(@Item, *Text) +EndProcedure + + +; The value of the extension Oid, a single INTEGER of up to 8 bytes, into +; *Value\q. #False if *Cert has none, or it isn't one. +Procedure.i BakaShrot_X509_GetExtensionInteger(*Cert.BakaShrot_X509Certificate, Oid.s, *Value.Quad) + Protected Index.i = BakaShrot_X509_FindExtension(*Cert, Oid) + Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement + + If Index < 0 + ProcedureReturn #False + EndIf + BakaShrot_Der_InitReader(@Reader, *Cert\Extensions(Index)\Value, *Cert\Extensions(Index)\ValueSize) + If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Integer, @Item) Or Not BakaShrot_Der_AtEnd(@Reader) + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_Der_GetInteger(@Item, *Value) +EndProcedure + + +; SHA-256 of the whole certificate, in hex: what `openssl x509 -fingerprint +; -sha256` shows (without its colons). +Procedure.s BakaShrot_X509_Fingerprint(*Cert.BakaShrot_X509Certificate) + Protected Dim Hash.a(#BakaShrot_Sha256_HashSize - 1) + + crypto_hash_sha256(@Hash(0), *Cert\Der, *Cert\DerSize) + ProcedureReturn BakaShrot_X509_Hex(@Hash(0), #BakaShrot_Sha256_HashSize) +EndProcedure + + +; A UTC time as "2026-11-13 14:03:59Z". +Procedure.s BakaShrot_X509_FormatTime(Seconds.q) + Protected Days.q, Rest.q, Year.q, Month.q, Day.q + + Days = Seconds / 86400 + Rest = Seconds % 86400 + If Rest < 0 + Days - 1 + Rest + 86400 + EndIf + BakaShrot_Der_CivilFromDays(Days, @Year, @Month, @Day) + ProcedureReturn RSet(Str(Year), 4, "0") + "-" + RSet(Str(Month), 2, "0") + "-" + RSet(Str(Day), 2, "0") + " " + + RSet(Str(Rest / 3600), 2, "0") + ":" + RSet(Str((Rest / 60) % 60), 2, "0") + ":" + RSet(Str(Rest % 60), 2, "0") + "Z" +EndProcedure + + +; *Cert described in a few lines, for people (tools, logs). +Procedure.s BakaShrot_X509_Describe(*Cert.BakaShrot_X509Certificate) + Protected Text.s, i.i, Flags.s + + Text = "Subject: " + BakaShrot_X509_NameToString(@*Cert\Subject) + #LF$ + + "Issuer: " + BakaShrot_X509_NameToString(@*Cert\Issuer) + #LF$ + + "Serial: " + *Cert\Serial + #LF$ + + "Valid: " + BakaShrot_X509_FormatTime(*Cert\NotBefore) + " to " + BakaShrot_X509_FormatTime(*Cert\NotAfter) + #LF$ + If *Cert\HasEd25519Key + Text + "Key: Ed25519 " + EncodeKeyToString(@*Cert\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + #LF$ + Else + Text + "Key: " + *Cert\KeyAlgorithm + " (not Ed25519)" + #LF$ + EndIf + If *Cert\HasBasicConstraints And *Cert\IsCa + If *Cert\PathLength >= 0 + Text + "CA: yes, path length " + Str(*Cert\PathLength) + #LF$ + Else + Text + "CA: yes" + #LF$ + EndIf + Else + Text + "CA: no" + #LF$ + EndIf + If *Cert\HasKeyUsage + Text + "Key usage: $" + Hex(*Cert\KeyUsage) + #LF$ + EndIf + For i = 0 To *Cert\ExtensionCount - 1 + Flags = "" + If *Cert\Extensions(i)\Critical + Flags = " (critical)" + EndIf + Text + "Extension: " + *Cert\Extensions(i)\Oid + Flags + ", " + Str(*Cert\Extensions(i)\ValueSize) + " bytes" + #LF$ + Next + Text + "SHA-256: " + BakaShrot_X509_Fingerprint(*Cert) + ProcedureReturn Text +EndProcedure + + +;- PEM + +; Size bytes at *Data as a PEM block: "-----BEGIN