ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Cryptography

🔐 End-to-end encryption and secure communication More...

Topics

 Keys Module
 ðŸ”‘ SSH key, GPG key, and key validation APIs

Detailed Description

🔐 End-to-end encryption and secure communication

Cryptographic operations, handshake protocol, and key management.

Connection security policy

Migrated from docs/crypto-policy.md into the rendered Doxygen topic set.

Connection security policy

Native clients and the browser use crypto_policy_resolve() from include/ascii-chat/crypto/policy.h. Mobile clients should call this same API. Its result is the existing ACIP mode bitmask: NONE (0), ENCRYPT (1), AUTH (2), or FULL (3). Authentication and payload encryption are independent.

Input Plain TCP / WS TLS / WSS / WebRTC DTLS
Default, no credentials ENCRYPT NONE
Password FULL FULL
Identity key or pinned server key FULL AUTH
Explicit encryption ENCRYPT ENCRYPT
Key and explicit no-encrypt AUTH AUTH
Password and explicit no-encrypt AUTH AUTH
No-auth, no credentials ENCRYPT NONE
No-auth and no-encrypt NONE NONE

An explicit encryption setting takes precedence over transport/password defaults. Supplying both encrypt and no-encrypt is an error. Supplying authentication material with no-auth is an error. Keys alone do not force a second encryption layer over TLS or DTLS. Config files, environment variables, and CLI flags retain that precedence: an enabled higher-priority encryption choice overrides the opposite lower-priority choice. Contradictory choices in the same layer are rejected.

For example, both peers can authenticate identities without ACIP payload encryption:

ascii-chat server --key server_key --client-keys client_key.pub --no-encrypt
ascii-chat client localhost --key client_key --server-key server_key.pub --no-encrypt

On plain transports the server must explicitly permit unencrypted payloads with --no-encrypt. A TLS listener permits TLS-only connections by default, but configured passwords or client allowlists still require authentication. Server --encrypt requires ACIP encryption; server --no-encrypt requires ACIP plaintext. Neither flag disables identity loading or signature checks.

Direct TCP and WebSocket clients begin with PROTOCOL_VERSION and the resolved mode. The server validates its requirements and echoes that mode. Nonzero modes continue through capability negotiation, key exchange and authentication. Application packets are sent only after negotiation succeeds. AUTH retains the completed crypto context for identity state while transports omit ENCRYPTED wrappers. WSS continues to encrypt those packets with TLS.

The browser passes its optional encryption override and configured credentials to WASM. JavaScript does not implement another policy decision table. Its connection state waits for authentication even when payload encryption is off. WebRTC always retains DTLS and negotiates the same policy independently for each media peer using acip_security_t. Passwords or explicit encryption add ACIP ENCRYPTED envelopes; auth-only verifies credentials without those envelopes. Media is admitted only after peer negotiation succeeds. Discovery signaling has its own credentials and security context. Both endpoints must support the new peer negotiation; older WebRTC peers must upgrade.

Discovery servers validate the proposed mode with crypto_policy_check_mode() before key exchange, on both TCP and WebSocket listeners. Native discovery clients resolve signaling mode independently of media-peer settings, advertise loaded identities, and retain the signaling crypto context until disconnect. Encrypted signaling includes keepalive packets. The native ACDS connector also accepts a security_policy in its configuration for explicit signaling overrides.

The CLI rejects --encrypt --no-encrypt and --no-auth with any authentication material. The shared policy also rejects these combinations for non-CLI callers. --key --server-key remains valid for mutual authentication. Explicit plaintext TCP/WS connections retain the ENCRYPTION DISABLED notice; TLS/DTLS connections do not produce that misleading warning.

For a future iOS caller, fill crypto_policy_t using the actual connection's transport security and user settings, call crypto_policy_resolve(), and use the returned bitmask in negotiation. Do not infer handshake completion from the encryption bit: AUTH also requires the complete handshake.

Validation:

cmake --build build --target ascii-chat test-crypto-policy
ctest --test-dir build -R '^crypto-policy$' --output-on-failure
uv run --frozen python tests/integration/crypto_policy.py /absolute/path/to/ascii-chat
# From web/web, with the rebuilt WASM bundle:
vp dev --config tests/network/crypto-policy.vite.config.ts
# In another terminal:
vp exec node tests/network/crypto-policy-live.mjs /absolute/path/to/ascii-chat http://127.0.0.1:30831

The live browser test records outgoing ACIP packet types, requires a PONG from the native server, and checks wrong-pin/password rejection before CONNECTED. Discovery cases use session-lookup round trips and verify server encryption and identity requirements. Multi-key cases pin the second configured server identity.

WebRTC validation (real native and browser DataChannels):

cmake --build build --target test-webrtc-security
ctest --test-dir build -R '^webrtc-security$' --output-on-failure
uv run --frozen python tests/integration/webrtc_security.py /absolute/path/to/ascii-chat
# From web/web:
vp exec playwright test --config tests/e2e/peer-security.config.ts

Records and replay

Migrated from docs/crypto-records.md into the rendered Doxygen topic set.

Authenticated packet records and rotation

The low-level crypto_encrypt uses a random 16-byte sender prefix followed by a big-endian counter. Its counter, keys, rekey state, and accounting fields are mutable and have no internal lock, so an integrating transport must serialize access to a shared context, including rekey operations. The prefix and counter avoid reuse when used correctly; they do not by themselves prevent replay. crypto_decrypt authenticates the supplied nonce and ciphertext but does not remember received nonces or validate a sender prefix. Packet callers use the authenticated record layer below, which rejects replay. The raw primitives remain available for handshake proofs and other crypto operations.

TCP, WebSocket, WebRTC, native QUIC, and browser WebTransport use the same packet codec, authenticated record format, and rekey coordinator. Packet framing and CRC validation live in lib/network/packet; ACIP policy and envelope handling live in lib/network/acip. The record and rekey engine live in lib/crypto and have no transport dependencies. Each crypto_context_t owns one serialized session with bounded control output. There is no alternate encrypted packet format.

The shared record codec uses the ACR1 encrypted envelope. The outer ACIP ENCRYPTED payload begins with an eight-byte network-order key epoch, followed by the existing ACIP nonce and authenticated ciphertext. Its encrypted prefix is 24 bytes: ACR1, sender direction, traffic class, delivery mode, one reserved zero byte, a network-order 64-bit sequence, and the same 64-bit epoch. The selector outside encryption is therefore checked against authenticated metadata. Reliable flows track their own monotonic receive sequence; media datagrams use separate 64-packet replay windows. Sequence and replay state span key changes.

The codec can prepare a next epoch only after the owner completes an authenticated DH exchange. An authenticated next-epoch packet proves possession of that prepared key even when its media flow overtakes control confirmation. The codec retains one previous receive context so delayed packets in other flows can still authenticate. The owner retires the previous key separately for each flow after an in-order retirement marker; late old-epoch datagrams on that flow are then stale. A second transition is rejected until all three flows retire, bounding retained key material. Retired contexts and all codec-owned key copies are wiped. A direct uncoordinated mutation of the borrowed key epoch is still rejected.

Native connections and browser WASM use the same session coordinator. A session mutex serializes record and rotation state; transport callbacks run after releasing it. Native writers and browser timers drive rotation even on idle connections. Packet and time thresholds use the existing crypto configuration (default one million packets or one hour; explicit test environments use one thousand packets or thirty seconds).

Only the server initiates the ephemeral DH exchange. A client reaching its threshold sends an encrypted, empty CRYPTO_REKEY_NEEDED (1113) control message. REKEY_REQUEST (1201) and REKEY_RESPONSE (1202) carry the existing 32-byte X25519 public keys under the old epoch. The server commits the prepared key and sends REKEY_COMPLETE (1203), containing one zero byte, under the new epoch. The client can authenticate media using its prepared key before COMPLETE arrives.

Each side queues CRYPTO_EPOCH_MARKER (1112) reliably on all three flows before later application packets. Its payload is the current epoch as a network-order 64-bit integer. Markers retire old receive keys independently; only after all three retire does a side send CRYPTO_EPOCH_ACK (1114), with the same epoch payload, on control. Another exchange requires both local retirement and the peer ACK. Internal packets never reach application dispatch, and application callers cannot submit them as media or control.

The coordinator preserves the minimum crypto and request intervals. It retains at most one authenticated incoming request until the receive-side interval expires, accommodating changed network delay without bypassing rate limiting. An exchange, including flow retirement, has a thirty-second timeout. Invalid roles, epochs, messages, output queue failures, and timeouts fail the connection. The session bounds internal output to sixteen logical control messages. The writer seals and drains them before later application sends; browser timers stop before crypto cleanup. Cleanup aborts pending DH and wipes retained keys.

Cryptography and Session Security

ascii-chat separates identity from session confidentiality. SSH/Ed25519, GPG-backed Ed25519, passwords, and pinned public keys authenticate policy; ephemeral key exchange derives the session encryption keys.

Handshake

The crypto handshake negotiates capabilities and parameters, performs the key exchange, authenticates the peer when policy requires it, and only then permits encrypted application packets. Transport TLS or DTLS authenticates its own endpoint but does not replace ACIP authentication and identity policy.

Records and replay

Encrypted records carry an epoch and sequence. The receiver authenticates and checks replay/order state before dispatching the inner ACIP packet. CRC and packet-family validation still apply at the packet layer. Never log passwords, private keys, session keys, or decrypted sensitive payloads.

Rekeying

Long-lived sessions can negotiate a new epoch. The old and new key state overlap only for the bounded transition; completion is acknowledged before old material is discarded. Rekey failures terminate the secure session rather than continuing with ambiguous key state.

Identity sources

Key loading and validation are documented in Key Management README. ACDS identity keys and server-key pinning are separate from the ephemeral encryption keys. Host-key changes require explicit trust policy; discovery metadata does not override an existing identity decision.

See also
topic_handshake
topic_keys
md_docs_2crypto-policy.html

Handshake Protocol

Handshake packets are dispatched before ordinary application traffic. The connection remains negotiating until the protocol version, crypto parameters, key exchange, and required authentication steps complete.

Steps

  1. Exchange protocol/version and crypto capabilities.
  2. Select compatible parameters and exchange ephemeral public keys.
  3. Derive the session secret and verify the peer identity when policy requires.
  4. Exchange completion/acknowledgement packets and enable encrypted records.
  5. Mark the network connection READY and admit application traffic.

The exact packet structures live in network/packet/packet.h and the crypto handshake headers. Transport readiness alone is insufficient: QUIC TLS, WebSocket TLS, or WebRTC DTLS must be followed by the ACIP security boundary.

Policy

Password authentication, identity signatures, server-key pinning, client-key allowlists, and ACDS verification are policy choices layered on the common exchange. --auth=false changes application authentication policy; it does not make transport ownership or packet framing unsafe.

Failure handling

Invalid versions, unsupported parameters, bad signatures, wrong passwords, replayed handshake messages, and timeout/cancellation errors fail the connection. They must not fall through to plaintext application traffic.

See also
topic_crypto
topic_network
include/ascii-chat/crypto/handshake

Crypto Module Organization

Overview

The lib/crypto/ module is the heart of ascii-chat's cryptographic implementation. It provides:

  • Core cryptography: X25519 key exchange, XSalsa20-Poly1305 encryption, Ed25519 signatures
  • Authentication: HMAC-based challenge-response, password derivation, signature verification
  • Key management: Loading, validating, and storing cryptographic keys from multiple sources
  • Integration: SSH agent, GPG agent, HTTPS key fetching, GitHub/GitLab key lookup
  • Protocol: Complete cryptographic handshake, session rekeying, message encryption/decryption

File Organization

The module is organized into several logical subsystems:

lib/crypto/
├── Core Cryptography
│ ├── crypto.c/h - Core crypto operations (encryption, key exchange, HMAC)
│ ├── crypto.h - Main public interface (1382 lines of documented functions)
│ ├── key_types.h - Key type definitions (private_key_t, key_purpose_t)
│ ├── pem.c/h - PEM format parsing (OpenSSH, PKCS8)
│ ├── regex.c/h - Regex utilities for key format detection
│ ├── sha1.c/h - SHA-1 implementation (for key fingerprinting)
│ └── common.c/h - Shared utilities
│
├── SSH Key Handling
│ ├── ssh/
│ │ ├── ssh_agent.c/h - SSH agent communication (signing, key lookup)
│ │ ├── ssh_keys.c/h - OpenSSH key format parsing and handling
│ │ └── [ssh_*.c] - SSH-specific operations
│ ├── keys_validation.c/h - SSH key validation and format checking
│ └── known_hosts.c/h - SSH-style known_hosts file management
│
├── GPG Key Handling
│ ├── gpg/
│ │ ├── gpg.h - Main GPG interface (aggregates submodules)
│ │ ├── agent.c/h - GPG agent communication
│ │ ├── export.c/h - Export keys from GPG keyring
│ │ ├── gpg_keys.c/h - GPG key format handling
│ │ ├── homedir.c/h - GPG home directory detection
│ │ ├── openpgp.c/h - OpenPGP format parsing
│ │ ├── signing.c/h - Signing operations with GPG
│ │ └── verification.c/h - GPG signature verification
│ └── [gpg_*.c] - Additional GPG operations
│
├── HTTPS & Key Fetching
│ ├── https_keys.c/h - HTTPS key fetching (using BearSSL)
│ ├── discovery_keys.c/h - ACDS discovery server key management
│ └── http/client/client.c/h - Low-level HTTPS client
│
├── Handshake & Protocol
│ ├── handshake/
│ │ ├── client.c/h - Client-side handshake implementation
│ │ ├── server.c/h - Server-side handshake implementation
│ │ └── common.c/h - Shared handshake utilities
│ ├── handshake_protocol.md - Protocol specification
│ └── [handshake_*.c] - Handshake state machines
│
├── Key Management
│ ├── keys.c/h - Master key loading and management
│ ├── discovery_keys.c/h - Discovery service key caching
│ └── key_types.h - Key structure definitions
│
└── Support Files
├── CMakeLists.txt - Build configuration
├── README.md - Module README (usage examples)
└── Doxygen docs/
├── crypto.dox - Comprehensive crypto reference
├── client_crypto.dox - Client-side crypto details
└── server_crypto.dox - Server-side crypto details
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for a specific mode.
Private identity-key material used for server authentication and signing.
Definition key_types.h:101

Subsystems

1. Core Cryptography (crypto.c/h)

Purpose: Low-level cryptographic operations

Key Functions:

Dependencies: libsodium only

Size: ~3000 lines (crypto.c + crypto.h)

Interfaces:

// Key exchange protocol (3 steps)
crypto_get_public_key(ctx, public_key_out); // Step 1: Send our key
crypto_set_peer_public_key(ctx, peer_public_key); // Step 2: Receive peer key
bool ready = crypto_is_ready(ctx); // Step 3: Ready for encryption
// Encryption/Decryption
crypto_encrypt(ctx, plaintext, plaintext_len, ciphertext_out, ...);
crypto_decrypt(ctx, ciphertext, ciphertext_len, plaintext_out, ...);
crypto_result_t crypto_set_peer_public_key(crypto_context_t *ctx, const uint8_t *peer_public_key)
Set peer's public key and compute shared secret (step 2 of handshake).
crypto_result_t crypto_encrypt(crypto_context_t *ctx, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext_out, size_t ciphertext_out_size, size_t *ciphertext_len_out)
Encrypt data using XSalsa20-Poly1305.
crypto_result_t crypto_get_public_key(const crypto_context_t *ctx, uint8_t *public_key_out)
Get public key for sending to peer (step 1 of handshake).
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
crypto_result_t crypto_decrypt(crypto_context_t *ctx, const uint8_t *ciphertext, size_t ciphertext_len, uint8_t *plaintext_out, size_t plaintext_out_size, size_t *plaintext_len_out)
Decrypt data using XSalsa20-Poly1305.

2. SSH Key Handling (ssh/*)

Purpose: Support for SSH keys and SSH agent integration

Submodules:

Key Functions:

  • ssh_agent_is_available() - Check if ssh-agent is running
  • ssh_agent_sign() - Request signature from agent
  • ssh_agent_list_keys() - List available keys in agent
  • ssh_keys_parse() - Parse OpenSSH key format
  • ssh_keys_export() - Export key to OpenSSH format

Integration Points:

  1. Key Loading: lib/crypto/keys.c loads SSH keys via ssh_keys_parse()
  2. Agent Signing: During handshake, if key is in agent, use ssh_agent_sign()
  3. Verification: Server verifies Ed25519 signature from client

Trust Flow:

User provides: --key ~/.ssh/id_ed25519
↓
Load via ssh_keys_parse() - Check if encrypted
↓
If encrypted & SSH agent available:
- Detect key in agent via ssh_agent_is_available()
- Set agent signing mode
↓
During handshake:
- Generate ephemeral X25519 key
- Sign ephemeral key with identity key
- If agent: use ssh_agent_sign()
- If not agent: use in-memory key (requires password)
bool ssh_agent_is_available(void)
Check if ssh-agent is running and available.
Definition ssh_agent.c:42
asciichat_error_t ssh_agent_sign(const public_key_t *public_key, const uint8_t *message, size_t message_len, uint8_t signature[64])
Sign data using SSH agent with the specified public key.
Definition ssh_agent.c:260

3. Known Hosts Management (known_hosts.c/h)

Purpose: SSH-style Trust On First Use (TOFU) verification

Location: ~/.ascii-chat/known_hosts (same format as SSH)

File Format:

hostname:port ssh-ed25519 AAAAC3Nza... # Server identity key (32 bytes)
127.0.0.1:27224 ssh-ed25519 BBBBC3Nza...

Key Functions:

  • known_hosts_verify() - Check if server key is in known_hosts
  • known_hosts_add() - Add new server key to known_hosts
  • known_hosts_update() - Update existing entry
  • known_hosts_remove() - Remove entry

Usage in Handshake:

Client receives: [ephemeral_key || identity_key || signature]
↓
Verify signature: ed25519_verify(identity_key, ephemeral_key, sig)
↓
Check known_hosts: known_hosts_verify("localhost:27224", identity_key)
↓
If key exists: Accept (already trusted)
If key new: Ask user: "Trust this server? [y/N]"
- Yes: Save to known_hosts
- No: Reject connection
If key changed: Warn "Server key changed! Possible MITM!"

Security Properties:

  • ✅ Protects against MITM on subsequent connections
  • ⚠ïļ First connection vulnerable to MITM (inherent to TOFU)
  • ✅ Detects key changes (alerts user)

4. GPG Key Handling (gpg/*)

Purpose: Support for GPG keys and GPG agent integration

Submodules:

Key Functions:

  • gpg_agent_sign() - Request signature from gpg-agent
  • gpg_export_public_key() - Export public key from keyring
  • gpg_verify_signature() - Verify GPG signature
  • gpg_keys_parse() - Parse GPG key format

Integration Points:

  1. Key Loading: lib/crypto/keys.c loads GPG keys via gpg_export_public_key()
  2. Agent Signing: If key is in gpg-agent, use gpg_agent_sign()
  3. Verification: Server verifies signature from client

Trust Flow:

User provides: --key gpg:zfogg
↓
Load via gpg_export_public_key()
↓
If GPG agent available:
- Set agent signing mode
- No passphrase prompt needed
↓
During handshake:
- Generate ephemeral X25519 key
- Sign ephemeral key with identity key
- Use gpg_agent_sign() for signature
int gpg_agent_sign(int handle_as_int, const char *keygrip, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
Sign a message using GPG agent.
Definition agent.c:161

5. HTTPS Key Fetching (https_keys.c/h, discovery_keys.c/h)

Purpose: Fetch public keys from HTTPS URLs (GitHub, GitLab, custom servers)

Supported Formats:

  • SSH public key format (RFC 4253) - e.g., GitHub API
  • OpenPGP armor - e.g., GitLab API
  • HTTPS URLs - e.g., discovery.ascii-chat.com/key.pub

Key Functions:

  • https_keys_fetch() - Fetch key from HTTPS URL using BearSSL
  • discovery_keys_verify() - Verify and cache discovery service keys
  • github_keys_fetch() - Special case for GitHub public keys API
  • gitlab_keys_fetch() - Special case for GitLab public keys API

Trust Model:

User provides: --server-key github:zfogg
↓
Fetch from: GET https://github.com/zfogg.keys
↓
Parse SSH keys from response
↓
During handshake:
- Verify server identity key against fetched key
- If matches: Accept
- If mismatch: Reject (possible MITM)

Security Properties:

  • ✅ Trust delegated to GitHub/GitLab (TLS + identity verification)
  • ✅ User can verify identity via GitHub profile
  • ⚠ïļ Requires HTTPS access to GitHub/GitLab
  • ✅ No local trust anchors needed

6. Key Validation (keys_validation.c/h)

Purpose: Validate cryptographic keys for security and format correctness

Key Functions:

  • keys_validate_format() - Check key format (SSH, PEM, OpenPGP)
  • keys_validate_size() - Verify key is correct size for algorithm
  • keys_validate_permissions() - Check file permissions (0600 on Unix)
  • keys_validate_expiration() - Check GPG key expiration
  • keys_validate_strength() - Verify key strength (e.g., 256-bit)

Validation Points:

  1. After loading: Validate format, size, permissions
  2. Before use: Validate expiration, strength
  3. During handshake: Validate peer key format and size

Integration:

// When loading a key
keys_validate_format(key_data, key_len); // Check format
keys_validate_size(key_data, key_len); // Check size
keys_validate_permissions(key_path); // Check file perms

7. Discovery Keys (discovery_keys.c/h)

Purpose: Manage ACDS (ASCII-Chat Discovery Service) server keys with caching

Cache Location: ~/.ascii-chat/acds_keys/<hostname>/

Key Functions:

  • discovery_keys_verify() - Verify and cache ACDS server key
  • discovery_keys_invalidate() - Invalidate cache on key change
  • discovery_keys_get_cache() - Get cached key

Trust Model for Official Server:

User wants: ACDS connection to discovery.ascii-chat.com
↓
discovery_keys_verify("discovery.ascii-chat.com", NULL, pubkey)
↓
If cached: Verify cache is valid, use cached key
If not cached:
- Download from https://discovery.ascii-chat.com/key.pub
- Trust without verification (official server)
- Cache key
↓
Use key to verify ACDS server identity
asciichat_error_t discovery_keys_verify(const char *acds_server, const char *key_spec, uint8_t pubkey_out[32])
Verify and load ACDS server public key.
bool valid
Definition fft.c:29

Trust Model for Third-Party Server:

User provides: --discovery-service-key https://acds.example.com/key.pub
↓
discovery_keys_verify("acds.example.com", "https://...", pubkey)
↓
Download and verify key (requires explicit specification)
Cache key
↓
Use key to verify ACDS server identity

8. Handshake Protocol (handshake/*)

Purpose: Complete cryptographic handshake implementation

Files:

Phases:

  1. Key Exchange: Exchange ephemeral public keys (X25519)
  2. Authentication: Prove identity via password/key/signature
  3. Session Setup: Negotiate algorithms, establish encryption keys
  4. Ready: Begin encrypted communication

Integration with Other Subsystems:

Handshake
├── Core Crypto (crypto.c)
│ ├── Generate ephemeral keys
│ ├── Compute shared secret
│ ├── Derive password key
│ └── Compute HMAC
│
├── SSH Keys (if --key ~/.ssh/id_ed25519)
│ ├── Load SSH key via ssh_keys_parse()
│ ├── Check SSH agent
│ └── Sign ephemeral key
│
├── GPG Keys (if --key gpg:zfogg)
│ ├── Export key from GPG keyring
│ ├── Check GPG agent
│ └── Request signature
│
├── Known Hosts (client-side, if --use-known-hosts)
│ ├── Verify server identity key
│ ├── Check for key changes
│ └── Prompt user if needed
│
├── GitHub Keys (if --server-key github:zfogg)
│ ├── Fetch keys from GitHub API
│ └── Verify server identity
│
└── Discovery Keys (if using ACDS)
├── Verify ACDS server key
└── Establish secure ACDS connection
if(!queries||!out||index >=DATABASE_QUERY_COUNT) return false

Data Flow Through Subsystems

Client Initialization

User provides: --key /path/to/key.pem --server-key github:zfogg --use-known-hosts
↓
1. Load identity key
keys.c:1 Load from file/agent/gpg
├── Detect format (SSH/PEM/GPG)
├── Parse with pem.c / ssh_keys.c / gpg/export.c
├── Validate with keys_validation.c
└── Store in memory
2. Load server verification key
https_keys.c:1 Fetch from HTTPS
├── Parse github:zfogg → https://github.com/zfogg.keys
├── Fetch via HTTPS using BearSSL
├── Parse SSH format
└── Store server_identity_key
3. Setup known_hosts verification
known_hosts.c:1 Load ~/.ascii-chat/known_hosts
└── Cache in memory
4. Initialize crypto
crypto.c:1 Initialize libsodium
├── Generate ephemeral X25519 keypair
├── Initialize nonce counter
└── Ready for handshake

Handshake Execution

Client Server
══════════════════════════════════════════════════════════════════════════
1. KEY_EXCHANGE_REQUEST
Send: ephemeral_pub || identity_pub || signature
↓
│ Receive
│ - Parse keys (ssh_keys.c / key_types.h)
│ - Verify signature (crypto.c: ed25519_verify)
│ - Check whitelist (keys_validation.c)
│ - Generate server ephemeral keys (crypto.c)
↓
Send: ephemeral_pub || identity_pub || signature
2. SHARED_SECRET_COMPUTED
crypto.c: DH(client_ephemeral, server_ephemeral)
↓
│ DH(server_ephemeral, client_ephemeral)
│ Same shared secret ✓
↓
3. AUTHENTICATION
If password mode:
- Compute HMAC: crypto_compute_auth_response()
If signature mode:
- SSH agent sign: ssh_agent_sign()
- GPG agent sign: gpg_agent_sign()
4. KNOWN_HOSTS VERIFICATION (client-side)
known_hosts_verify("localhost:27224", server_identity_key)
├── In cache? Accept ✓
├── New key? Ask user & save
└── Key changed? Warn & reject
5. READY FOR ENCRYPTION
crypto.c: crypto_is_ready() = true
crypto_result_t crypto_derive_password_key(crypto_context_t *ctx, const char *password)
Derive key from password using Argon2id.
crypto_result_t crypto_compute_auth_response(const crypto_context_t *ctx, const uint8_t nonce[AUTH_CHALLENGE_SIZE], uint8_t hmac_out[HMAC_SHA256_SIZE])
return true
Definition queries.h:13

Integration Patterns

Pattern 1: SSH Key with SSH Agent

User: ./ascii-chat client --key ~/.ssh/id_ed25519
Flow:
1. ssh_keys_parse() detects key is encrypted
3. During handshake:
- ssh_agent_sign() requests signature from agent
- No passphrase prompt needed ✓

Pattern 2: GPG Key with GPG Agent

User: ./ascii-chat client --key gpg:zfogg
Flow:
1. gpg_export_public_key() loads key from GPG keyring
2. GPG agent available?
- Yes: gpg_agent_sign() in handshake ✓
- No: Prompt for passphrase

Pattern 3: GitHub Key Verification

User: ./ascii-chat client --server-key github:zfogg
Flow:
1. https_keys_fetch("https://github.com/zfogg.keys")
2. Parse SSH public keys from response
3. During handshake:
- Verify server's identity key matches fetched key
- Blocks MITM attacks ✓

Pattern 4: Known Hosts Trust On First Use

User: ./ascii-chat client --use-known-hosts
Flow:
1. First connection:
- Verify server identity key signature ✓
- Key not in known_hosts → Ask user
- User confirms → Save to known_hosts ✓
2. Second connection:
- Verify identity key signature ✓
- Key in known_hosts → Accept ✓
3. If server key changes:
- Warn "Server key has changed!" ⚠ïļ
- Possible MITM attack

Pattern 5: Discovery Keys with ACDS

User: ./ascii-chat client --discovery-service acds.example.com
Flow:
1. discovery_keys_verify("acds.example.com", NULL, pubkey)
2. If official server:
- Download https://discovery.ascii-chat.com/key.pub
- Cache without verification ✓
3. Connect to ACDS server:
- Verify ACDS identity with cached key ✓
4. ACDS provides session discovery

File Locations Summary

Source Code:

  • lib/crypto/*.c/*.h - Implementation files

Configuration & Keys:

  • ~/.ascii-chat/ - Config directory
  • ~/.ascii-chat/authorized_clients.txt - Server whitelist
  • ~/.ascii-chat/known_hosts - Known servers (SSH-style)
  • ~/.ascii-chat/acds_keys/ - Cached ACDS server keys
  • ~/.ssh/ - User SSH keys
  • ~/.gnupg/ - User GPG keyring

Headers (Public API):

Documentation:

Building & Testing

Build Configuration:

# From CMakeLists.txt
add_library(ascii-chat-lib-crypto
lib/crypto/crypto.c
lib/crypto/handshake/client.c
lib/crypto/handshake/server.c
lib/crypto/handshake/common.c
lib/crypto/ssh/ssh_agent.c
lib/crypto/ssh/ssh_keys.c
lib/crypto/gpg/agent.c
lib/crypto/gpg/export.c
# ... etc
)
target_link_libraries(ascii-chat-lib-crypto libsodium BearSSL)

Dependencies:

  • libsodium - Modern cryptography (X25519, XSalsa20-Poly1305, Argon2id, Ed25519)
  • BearSSL - TLS for HTTPS key fetching
  • OpenSSL - System integration (gpg-agent communication)
  • libgpgme (optional) - GPG operations

Testing:

# Unit tests for crypto operations
ctest --test-dir build -R crypto
# Handshake protocol tests
ctest --test-dir build -R handshake
# SSH key tests
ctest --test-dir build -R ssh
# Known hosts tests
ctest --test-dir build -R known_hosts

Performance Considerations

Initialization:

  • crypto_init() - ~100Ξs (libsodium init + key generation)
  • ssh_keys_parse() - ~50Ξs (format detection + parsing)
  • gpg_export_public_key() - ~500ms (calls external gpg process)

Handshake:

  • Key exchange - ~500Ξs (X25519 computation)
  • HMAC computation - ~50Ξs (SHA256)
  • SSH agent sign - ~1ms (IPC + SSH protocol)
  • GPG agent sign - ~50ms (IPC + GPG protocol)
  • HTTPS key fetch - ~200ms (network + TLS)

Per-Packet:

  • Encryption - ~20Ξs per KB (XSalsa20)
  • Decryption - ~20Ξs per KB (XSalsa20)
  • MAC verification - ~10Ξs (Poly1305)

Optimization Tips:

  1. Cache SSH agent public keys (avoid repeated queries)
  2. Cache HTTPS fetched keys (use discovery_keys for ACDS)
  3. Use password auth for repeated connections (faster than SSH agent)
  4. Prefer SSH agent over GPG agent (faster protocol)

Security Properties

Encryption:

  • ✅ XSalsa20-Poly1305 (authenticated encryption)
  • ✅ Constant-time MAC verification
  • ✅ Unique nonces (session_id || counter)
  • ✅ Automatic rekeying (1 hour or 1M packets)

Key Exchange:

  • ✅ X25519 ephemeral keys (forward secrecy)
  • ✅ Signature-based authentication (when provided)
  • ✅ Password-based optional encryption (Argon2id KDF)

Authentication:

  • ✅ HMAC-SHA256 challenge-response
  • ✅ Ed25519 signatures
  • ✅ SSH agent integration (keys never in memory)
  • ✅ GPG agent integration (keys never in memory)

Vulnerabilities (Known & Fixed):

  • ✅ Replay attacks (fixed via session ID in nonce)
  • ✅ Timing attacks (fixed via sodium_memcmp)
  • ✅ Code duplication (fixed via shared functions)
  • See docs/topics/crypto.dox for full vulnerability disclosure

Future Enhancements

  1. Post-Quantum Cryptography
    • Hybrid X25519-Kyber1024 key exchange
    • Hybrid Ed25519-Dilithium3 signatures
    • Status: RFC in progress
  2. Verification Server
    • Global key registry (like Certificate Authorities)
    • Key pinning without pre-sharing
    • Status: Planned (Issue #82)
  3. Hardware Security Modules
    • PKCS#11 support
    • YubiKey integration
    • Status: Research phase
  4. Double Ratchet Protocol
    • Signal-style per-message forward secrecy
    • Status: Deferred (session rekeying sufficient)
See also
Cryptography Reference
Client-Side Crypto Details
Server-Side Crypto Details
Handshake Protocol Specification