ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
Crypto Module

🔐 Core cryptographic operations for ascii-chat More...

Files

file  crypto.c
 🔐 Core cryptography: encryption/decryption, key exchange, authentication, and session rekeying with BearSSL
file  discovery_keys.c
 Discovery Server Public Key Trust Management Implementation.
file  agent.c
 GPG agent connection and communication implementation.
file  export.c
 GPG public key export implementation.
file  homedir.c
 Temporary GPG homedir management implementation.
file  openpgp.c
 OpenPGP (RFC 4880) packet format parser implementation.
file  signing.c
 GPG signing operations implementation.
file  verification.c
 GPG signature verification implementation.
file  known_hosts.c
 📜 SSH known_hosts file parser for host key verification and trust management
file  pem.c
 📄 PEM format encoding/decoding utilities for certificates and keys (adapted from BearSSL)
file  regex.c
 PCRE2-based regex patterns for cryptographic parsing.
file  discovery_keys.h
 Discovery Server Public Key Trust Management.
file  agent.h
 GPG agent connection and communication interface.
file  export.h
 GPG public key export interface.
file  gpg.h
 GPG operations - main header.
file  homedir.h
 Temporary GPG homedir management for isolated key operations.
file  openpgp.h
 OpenPGP (RFC 4880) packet format parser.
file  signing.h
 GPG message signing interface.
file  verification.h
 GPG signature verification interface.
file  known_hosts.h
 Known hosts management for MITM attack prevention.
file  pem.h
 BearSSL PEM and trust anchor utilities adapted for in-memory data.
file  regex.h
 PCRE2-based regex patterns for cryptographic parsing.

Data Structures

struct  crypto_context_t
 Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying. More...
struct  openpgp_packet_header_t
 The framing fields needed to locate and classify one OpenPGP packet body. More...
struct  openpgp_public_key_t
 The parsed identity portion of an OpenPGP public-key packet. More...
struct  openpgp_secret_key_t
 The parsed public and private material from an OpenPGP secret-key packet. More...
struct  anchor_list
 Vector type for trust anchors. More...

Macros

#define SSH_KEY_TYPE_LENGTH_SIZE   4
#define SSH_KEY_TYPE_STRING_SIZE   11
#define SSH_KEY_PUBLIC_KEY_LENGTH_SIZE   4
#define SSH_KEY_PUBLIC_KEY_SIZE   32
#define SSH_KEY_HEADER_SIZE   (SSH_KEY_TYPE_LENGTH_SIZE + SSH_KEY_TYPE_STRING_SIZE + SSH_KEY_PUBLIC_KEY_LENGTH_SIZE + SSH_KEY_PUBLIC_KEY_SIZE)
#define CRYPTO_KEY_SIZE   32
 Ed25519 key size in bytes.
#define CRYPTO_FINGERPRINT_SIZE   32
 Ed25519 key fingerprint size in bytes.
#define SSH_KEY_PERMISSIONS_MASK   (S_IRWXG | S_IRWXO)
#define SSH_KEY_RECOMMENDED_PERMISSIONS   0600

Typedefs

typedef struct crypto_context_t crypto_context_t
 Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.

Enumerations

enum  crypto_result_t {
  CRYPTO_OK = 0 , CRYPTO_ERROR_INIT_FAILED = -1 , CRYPTO_ERROR_INVALID_PARAMS = -2 , CRYPTO_ERROR_MEMORY = -3 ,
  CRYPTO_ERROR_LIBSODIUM = -4 , CRYPTO_ERROR_KEY_GENERATION = -5 , CRYPTO_ERROR_PASSWORD_DERIVATION = -6 , CRYPTO_ERROR_ENCRYPTION = -7 ,
  CRYPTO_ERROR_DECRYPTION = -8 , CRYPTO_ERROR_INVALID_MAC = -9 , CRYPTO_ERROR_BUFFER_TOO_SMALL = -10 , CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE = -11 ,
  CRYPTO_ERROR_NONCE_EXHAUSTED = -12 , CRYPTO_ERROR_REKEY_IN_PROGRESS = -13 , CRYPTO_ERROR_REKEY_FAILED = -14 , CRYPTO_ERROR_REKEY_RATE_LIMITED = -15
}
 Cryptographic operation result codes. More...

Variables

br_x509_trust_anchor * anchor_list::buf
size_t anchor_list::ptr
size_t anchor_list::len

Known Hosts Management

const char * get_known_hosts_path (void)
 Get the path to the known_hosts file.
asciichat_error_t add_known_host (const char *server_ip, uint16_t port, const uint8_t server_key[32])
 Add server to known_hosts.
asciichat_error_t remove_known_host (const char *server_ip, uint16_t port)
 Remove server from known_hosts.

Core Initialization and Setup

crypto_result_t crypto_init (crypto_context_t *ctx)
 Initialize libsodium and crypto context.
crypto_result_t crypto_init_with_password (crypto_context_t *ctx, const char *password)
 Initialize with password-based encryption.
void crypto_destroy (crypto_context_t *ctx)
 Cleanup crypto context with secure memory wiping.
crypto_result_t crypto_generate_keypair (crypto_context_t *ctx)
 Generate new X25519 key pair for key exchange.

Key Exchange Protocol

Automatic HTTPS-like key exchange using X25519 Diffie-Hellman. Both parties exchange ephemeral public keys and compute a shared secret.

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).
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).
bool crypto_is_ready (const crypto_context_t *ctx)
 Check if key exchange is complete and ready for encryption.

Password-Based Encryption

Optional additional encryption layer using password-derived keys. Uses Argon2id for memory-hard key derivation, providing resistance to offline brute-force attacks.

crypto_result_t crypto_validate_password (const char *password)
 Validate password length requirements.
crypto_result_t crypto_derive_password_key (crypto_context_t *ctx, const char *password)
 Derive key from password using Argon2id.
bool crypto_verify_password (const crypto_context_t *ctx, const char *password)
 Verify password matches stored salt/key.
crypto_result_t crypto_derive_password_encryption_key (const char *password, uint8_t encryption_key[32])
 Derive deterministic encryption key from password for handshake.

Encryption/Decryption Operations

Encrypt/decrypt data using XSalsa20-Poly1305 (via libsodium secretbox). Automatically handles nonce generation and MAC verification.

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_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.

Utility Functions

const char * crypto_result_to_string (crypto_result_t result)
 Convert crypto result to human-readable string.
void crypto_get_status (const crypto_context_t *ctx, char *status_buffer, size_t buffer_size)
 Get crypto context status information for debugging.
bool crypto_secure_compare (const uint8_t *lhs, const uint8_t *rhs, size_t len)
 Secure constant-time comparison of byte arrays.
crypto_result_t crypto_random_bytes (uint8_t *buffer, size_t len)
 Generate cryptographically secure random bytes.

Authentication and Handshake

HMAC-based authentication using HMAC-SHA256. Used for password authentication and challenge-response protocols.

crypto_result_t crypto_generate_nonce (uint8_t nonce[32])
 Generate random nonce for authentication.
crypto_result_t crypto_compute_hmac (crypto_context_t *ctx, const uint8_t key[32], const uint8_t data[32], uint8_t hmac[32])
 Compute HMAC-SHA256 for fixed 32-byte data.
crypto_result_t crypto_compute_hmac_ex (const crypto_context_t *ctx, const uint8_t key[32], const uint8_t *data, size_t data_len, uint8_t hmac[32])
 Compute HMAC-SHA256 for variable-length data.
bool crypto_verify_hmac (const uint8_t key[32], const uint8_t data[32], const uint8_t expected_hmac[32])
 Verify HMAC-SHA256 for fixed 32-byte data.
bool crypto_verify_hmac_ex (const uint8_t key[32], const uint8_t *data, size_t data_len, const uint8_t expected_hmac[32])
 Verify HMAC-SHA256 for variable-length data.

High-Level Authentication Helpers

Authentication helpers that bind password/key authentication to the DH key exchange, preventing man-in-the-middle attacks.

crypto_result_t crypto_compute_auth_response (const crypto_context_t *ctx, const uint8_t nonce[32], uint8_t hmac_out[32])
 Compute authentication response HMAC bound to DH shared_secret.
bool crypto_verify_auth_response (const crypto_context_t *ctx, const uint8_t nonce[32], const uint8_t expected_hmac[32])
 Verify authentication response HMAC bound to DH shared_secret.
crypto_result_t crypto_create_auth_challenge (crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
 Create authentication challenge packet.
crypto_result_t crypto_process_auth_challenge (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
 Process authentication challenge packet.
crypto_result_t crypto_process_auth_response (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
 Process authentication response packet.

Network Integration Helpers

Packet creation and processing functions for network transmission. Handles packet formatting, encryption, and decryption automatically.

crypto_result_t crypto_create_public_key_packet (const crypto_context_t *ctx, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
 Create public key packet for network transmission.
crypto_result_t crypto_process_public_key_packet (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len)
 Process received public key packet from peer.
crypto_result_t crypto_create_encrypted_packet (crypto_context_t *ctx, const uint8_t *data, size_t data_len, uint8_t *packet_out, size_t packet_size, size_t *packet_len_out)
 Create encrypted data packet for network transmission.
crypto_result_t crypto_process_encrypted_packet (crypto_context_t *ctx, const uint8_t *packet, size_t packet_len, uint8_t *data_out, size_t data_size, size_t *data_len_out)
 Process received encrypted packet from peer.

Shared Cryptographic Operations

Low-level cryptographic operations used by both client and server for authentication and key exchange.

asciichat_error_t crypto_compute_password_hmac (crypto_context_t *ctx, const uint8_t *password_key, const uint8_t *nonce, const uint8_t *shared_secret, uint8_t *hmac_out)
 Compute password-based HMAC for authentication.
asciichat_error_t crypto_verify_peer_signature (const uint8_t *peer_public_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, const uint8_t *signature)
 Verify peer's signature on ephemeral key.
asciichat_error_t crypto_sign_ephemeral_key (const private_key_t *private_key, const uint8_t *ephemeral_key, size_t ephemeral_key_size, uint8_t *signature_out)
 Sign ephemeral key with private key.
void crypto_combine_auth_data (const uint8_t *hmac, const uint8_t *challenge_nonce, uint8_t *combined_out)
 Combine HMAC and challenge nonce for transmission.
void crypto_extract_auth_data (const uint8_t *combined_data, uint8_t *hmac_out, uint8_t *challenge_out)
 Extract HMAC and challenge nonce from combined data.

Session Rekeying Protocol

Periodic key rotation to limit exposure if keys are compromised. Rekeys after time threshold (default: 1 hour) OR packet count threshold (default: 1 million), whichever comes first.

Note
Test environment detection: If TESTING environment variable is set, rekey thresholds are reduced to 30 seconds / 1000 packets for faster testing.
Rekeying flow:
  1. Initiator calls crypto_rekey_init() and sends REKEY_REQUEST
  2. Responder processes request, calls crypto_rekey_process_request(), sends REKEY_RESPONSE
  3. Initiator processes response, calls crypto_rekey_process_response(), sends REKEY_COMPLETE
  4. Responder verifies REKEY_COMPLETE decrypts with new key, calls crypto_rekey_commit()
  5. Initiator calls crypto_rekey_commit() after receiving confirmation
Old keys remain active until REKEY_COMPLETE is verified, ensuring no service interruption.
bool crypto_should_rekey (const crypto_context_t *ctx)
 Check if rekeying should be triggered based on time or packet count thresholds.
crypto_result_t crypto_rekey_init (crypto_context_t *ctx)
 Initiate rekeying by generating new ephemeral keys.
crypto_result_t crypto_rekey_process_request (crypto_context_t *ctx, const uint8_t *peer_new_public_key)
 Process REKEY_REQUEST from peer (responder side).
crypto_result_t crypto_rekey_process_response (crypto_context_t *ctx, const uint8_t *peer_new_public_key)
 Process REKEY_RESPONSE from peer (initiator side).
crypto_result_t crypto_rekey_commit (crypto_context_t *ctx)
 Commit to new keys after successful REKEY_COMPLETE.
void crypto_rekey_abort (crypto_context_t *ctx)
 Abort rekeying and fallback to old keys.
void crypto_get_rekey_status (const crypto_context_t *ctx, char *status_buffer, size_t buffer_size)
 Get the current rekeying state for debugging/logging.
#define REKEY_MIN_INTERVAL   (3LL * NS_PER_SEC_INT)
 Minimum time interval between rekey requests (3 seconds in nanoseconds for testing, 60 for production).
#define REKEY_DEFAULT_TIME_THRESHOLD   (3600LL * NS_PER_SEC_INT)
 Default rekey time threshold (1 hour in nanoseconds).
#define REKEY_DEFAULT_PACKET_THRESHOLD   1000000
 Default rekey packet threshold (1 million packets).
#define REKEY_TEST_TIME_THRESHOLD   (30LL * NS_PER_SEC_INT)
 Test mode rekey time threshold (30 seconds in nanoseconds).
#define REKEY_TEST_PACKET_THRESHOLD   1000
 Test mode rekey packet threshold (1000 packets).
#define REKEY_MAX_FAILURE_COUNT   10
 Maximum consecutive rekey failures before giving up.
#define REKEY_MIN_REQUEST_INTERVAL   (60LL * NS_PER_SEC_INT)
 Minimum interval between rekey requests (60 seconds in nanoseconds, DDoS protection).

GPG Agent Connection Management

int gpg_agent_connect (void)
 Connect to gpg-agent.
void gpg_agent_disconnect (int sock)
 Disconnect from gpg-agent.
bool gpg_agent_is_available (void)
 Check if GPG agent is available.

GPG Agent Signing Operations

int gpg_agent_sign (int sock, 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.

GPG Key Export

int gpg_get_public_key (const char *key_id, uint8_t *public_key_out, char *keygrip_out)
 Get public key from GPG keyring by key ID.

PGP Armored Format Parsing

asciichat_error_t openpgp_parse_armored_pubkey (const char *armored_text, uint8_t ed25519_pk[32])
 Parse PGP armored key block and extract Ed25519 public key.
asciichat_error_t openpgp_parse_binary_pubkey (const uint8_t *data, size_t data_len, uint8_t ed25519_pk[32])
asciichat_error_t openpgp_parse_armored_seckey (const char *armored_text, uint8_t ed25519_pk[32], uint8_t ed25519_sk[32])
 Parse PGP armored secret key block and extract Ed25519 keypair.
asciichat_error_t openpgp_parse_binary_seckey (const uint8_t *data, size_t data_len, uint8_t ed25519_pk[32], uint8_t ed25519_sk[32])

OpenPGP Packet Parsing

asciichat_error_t openpgp_parse_packet_header (const uint8_t *data, size_t data_len, openpgp_packet_header_t *header)
 Parse OpenPGP packet header.
asciichat_error_t openpgp_parse_public_key_packet (const uint8_t *packet_body, size_t body_len, openpgp_public_key_t *pubkey)
 Parse OpenPGP Public Key Packet (tag 6).
asciichat_error_t openpgp_parse_secret_key_packet (const uint8_t *packet_body, size_t body_len, openpgp_secret_key_t *seckey)
 Parse OpenPGP Secret Key Packet (tag 5).
asciichat_error_t openpgp_extract_ed25519_from_mpi (const uint8_t *mpi, size_t mpi_len, uint8_t ed25519_pk[32])
 Extract Ed25519 public key from MPI-encoded data.

Base64 Decoding for PGP Armor

asciichat_error_t openpgp_base64_decode (const char *base64, size_t base64_len, uint8_t **binary_out, size_t *binary_len)
 Decode PGP armored base64 data.

GPG Signing Operations

int gpg_sign_with_key (const char *key_id, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
 Sign a message using GPG key and return OpenPGP signature.
int gpg_sign_detached_ed25519 (const char *key_id, const uint8_t *message, size_t message_len, uint8_t signature_out[ED25519_SIGNATURE_SIZE])
 Sign message with GPG and extract raw Ed25519 signature.

GPG Signature Verification

int gpg_verify_detached_ed25519 (const char *key_id, const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE])
 Verify Ed25519 signature using GPG binary.
int gpg_verify_signature (const uint8_t *public_key, const uint8_t *message, size_t message_len, const uint8_t *signature)
 Verify Ed25519 signature using libgcrypt (no GPG binary required).
int gpg_verify_signature_with_binary (const uint8_t *signature, size_t signature_len, const uint8_t *message, size_t message_len, const char *expected_key_id)
 Verify OpenPGP signature using GPG binary.

Known Hosts Verification

asciichat_error_t check_known_host (const char *server_ip, uint16_t port, const uint8_t server_key[32])
 Check if server key is in known_hosts.
asciichat_error_t check_known_host_with_key (const char *server_ip, uint16_t port, const uint8_t server_key[32], uint8_t expected_key[32], bool *has_expected_key)
asciichat_error_t check_known_host_no_identity (const char *server_ip, uint16_t port)
 Check known_hosts for servers without identity key (no-identity entries).

User Interaction

bool display_mitm_warning (const char *server_ip, uint16_t port, const uint8_t expected_key[32], const uint8_t received_key[32])
 Display MITM warning with key comparison and prompt user for confirmation.
bool prompt_unknown_host (const char *server_ip, uint16_t port, const uint8_t server_key[32])
 Interactive prompt for unknown host - returns true if user wants to add, false to abort.
bool prompt_unknown_host_no_identity (const char *server_ip, uint16_t port)
 Interactive prompt for unknown host without identity key - returns true if user wants to continue, false to abort.

Key Fingerprinting

void compute_key_fingerprint (const uint8_t key[32], char fingerprint[(32 *2+1)])
 Compute SHA256 fingerprint of Ed25519 key for display.

Cleanup

void known_hosts_destroy (void)
 Cleanup function to free cached known_hosts path.

Trust Anchor Management

Vector type for trust anchors

size_t read_trust_anchors_from_memory (anchor_list *dst, const unsigned char *pem_data, size_t pem_len)
 Read trust anchors from PEM-encoded data in memory.
void free_ta_contents (br_x509_trust_anchor *ta)
 Free the contents of a trust anchor.
#define ANCHOR_LIST_INIT   {NULL, 0, 0}
 Initializer for anchor_list.

SSH Agent Detection

bool ssh_agent_is_available (void)
 Check if ssh-agent is running and available.

SSH Agent Key Management

asciichat_error_t ssh_agent_add_key (const private_key_t *private_key, const char *key_path)
 Add a private key to ssh-agent.
bool ssh_agent_has_key (const public_key_t *public_key)
 Check if a public key is already in ssh-agent.
asciichat_error_t ssh_agent_get_key (const public_key_t *public_key, private_key_t *key_out)
 Retrieve a private key from ssh-agent by matching public key.
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.

Encryption Size Limits

#define CRYPTO_MAX_PLAINTEXT_SIZE   ((size_t)1024 * 1024)
 Maximum plaintext size (1MB).
#define CRYPTO_MAX_CIPHERTEXT_SIZE   (CRYPTO_MAX_PLAINTEXT_SIZE + CRYPTO_MAC_SIZE)
 Maximum ciphertext size (plaintext + MAC, ~1MB + 16 bytes).

Hex String Size Constants

#define CRYPTO_HEX_KEY_SIZE   64
 Hex string size for 32-byte key (64 hex characters).
#define CRYPTO_HEX_KEY_SIZE_NULL   65
 Hex string size for 32-byte key with null terminator (65 bytes).
#define CRYPTO_HEX_KEY64_SIZE   128
 Hex string size for 64-byte key (128 hex characters).
#define CRYPTO_HEX_KEY64_SIZE_NULL   129
 Hex string size for 64-byte key with null terminator (129 bytes).

Cryptographic String Literals

#define SSH_ED25519_KEY_TYPE   "ssh-ed25519"
 SSH Ed25519 key type string ("ssh-ed25519").
#define X25519_KEY_TYPE   "x25519"
 X25519 key type string ("x25519").
#define NO_IDENTITY_MARKER   "no-identity"
 No-identity entry marker ("no-identity").

OpenPGP Constants

The framing fields needed to locate and classify one OpenPGP packet body

The parsed identity portion of an OpenPGP public-key packet

The parsed public and private material from an OpenPGP secret-key packet

#define OPENPGP_TAG_PUBLIC_KEY   6
 OpenPGP packet tag for Public Key Packet.
#define OPENPGP_TAG_SECRET_KEY   5
 OpenPGP packet tag for Secret Key Packet.
#define OPENPGP_TAG_USER_ID   13
 OpenPGP packet tag for User ID Packet.
#define OPENPGP_TAG_SIGNATURE   2
 OpenPGP packet tag for Signature Packet.
#define OPENPGP_ALGO_EDDSA   22
 OpenPGP algorithm ID for EdDSA (Ed25519).
#define OPENPGP_ALGO_ECDH   18
 OpenPGP algorithm ID for ECDH (Curve25519).

Detailed Description

🔐 Core cryptographic operations for ascii-chat

This header provides the core cryptographic operations for secure communication in ascii-chat, including key exchange, encryption/decryption, authentication, and session rekeying.

The interface provides:

  • Cryptographic context management
  • X25519 key exchange (Diffie-Hellman)
  • XSalsa20-Poly1305 encryption/decryption
  • Argon2id password-based key derivation
  • HMAC-SHA256 authentication
  • Session rekeying protocol
Note
Key Exchange: Uses ephemeral X25519 keys for perfect forward secrecy. Each connection generates new keys automatically.
Encryption: XSalsa20-Poly1305 provides authenticated encryption with automatic MAC verification. Nonces are generated as session_id || counter to avoid nonce reuse; this alone does not detect replayed ciphertext.
Password Authentication: Optional password-based encryption using Argon2id for memory-hard key derivation. Passwords are bound to DH shared secrets to prevent MITM attacks.
Rekeying: Automatic periodic key rotation after time threshold (1 hour) OR packet count threshold (1 million), whichever comes first. Test mode uses reduced thresholds (30 seconds / 1000 packets).
Test Environment: Automatically detects test environment via TESTING or TESTING environment variables and adjusts thresholds accordingly.
Byte Order: Client must convert network byte order to host byte order for crypto parameters. Server uses host byte order directly.
Key Exchange Formats:
  • Simple format: Only ephemeral public key (when server has no identity key)
  • Authenticated format: Ephemeral key + identity key + signature (when server has identity key)
Warning
Always use crypto_secure_compare() for comparing sensitive data (keys, MACs, HMACs). Do NOT use regular memcmp() as it is vulnerable to timing attacks.
Nonce counter starts at 1 (0 is reserved for testing). Returns CRYPTO_ERROR_NONCE_EXHAUSTED if counter reaches 0 or UINT64_MAX (extremely unlikely, but triggers rekeying).
Password salt is deterministic ("ascii-chat-password-salt-v1") for consistent key derivation across client/server. Only use for session encryption, not long-term storage.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides GPG agent (gpg-agent) integration for signing operations with GPG keys. Allows private keys to stay in GPG agent without being loaded into application memory.

Note
GPG agent protocol: Implements Assuan protocol for communicating with gpg-agent. Keys stay in agent and are never loaded into application memory.
Platform support:
  • Unix: Uses GPG_AGENT_INFO or connects to standard socket (~/.gnupg/S.gpg-agent)
  • Windows: Connects to standard named pipe (Gpg4win installs gpg-agent as service)
Key format: Only Ed25519 GPG keys are supported. RSA/ECDSA GPG keys are NOT supported.
Keygrip: GPG uses keygrips (40-char hex strings) to identify keys in the agent. Keygrips are computed from public key material and are stable identifiers.
Agent detection: Checks for agent socket/pipe existence and accessibility. On Unix, verifies socket is accessible. On Windows, checks for named pipe.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides functions for exporting public keys from GPG keyring. Supports retrieving Ed25519 public keys and keygrips for use in authentication and signing operations.

Note
Key export: Uses gpg --export to extract public key from local keyring. Parses OpenPGP packet format to extract Ed25519 public key material.
Keygrip extraction: Optionally extracts keygrip for use with GPG agent. Keygrip is a stable 40-char hex identifier computed from public key.
Key ID formats: Supports short (8-char), long (16-char), and full (40-char) key IDs. Accepts key IDs with or without "0x" prefix.
Ed25519 only: Only Ed25519 GPG keys are supported. RSA/ECDSA keys will cause export to fail.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides the complete GPG interface by including all submodule headers. Users can include this single header to access all GPG functionality.

Submodules:

Implements parsing of OpenPGP packet format (RFC 4880) for extracting Ed25519 public keys from PGP armored key blocks.

Supported features:

  • PGP armored format (--—BEGIN PGP PUBLIC KEY BLOCK--—)
  • Base64 decoding of armored data
  • OpenPGP packet header parsing (old and new formats)
  • Public Key Packet (tag 6) parsing
  • Ed25519 (algorithm 22) key extraction
Note
Limitations:
  • Only supports Ed25519 keys (algorithm 22)
  • Only parses public key packets (tag 6)
  • Does not verify signatures or checksums
  • Does not support encrypted keys
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
January 2026

This header provides GPG signing operations for creating detached signatures. Supports both OpenPGP-formatted signatures and raw Ed25519 signatures extracted from GPG output.

Note
Signing method: Uses gpg --detach-sign to create detached signatures. Signatures are separate from message data (not inline signatures).
Key requirements: Only Ed25519 GPG keys are supported. RSA/ECDSA keys will cause signing operations to fail.
Output formats:
GPG binary: Requires gpg binary in PATH for all operations. Returns error if GPG is not installed or not accessible.
Key passphrase: If key is encrypted, GPG may prompt for passphrase. Use ssh-agent or gpg-agent for password-free signing, or set $ASCII_CHAT_KEY_PASSWORD environment variable.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides GPG signature verification operations supporting both GPG binary-based verification and direct cryptographic verification via libgcrypt. Handles both raw Ed25519 signatures and OpenPGP-formatted signatures.

Note
Verification methods:
  • GPG binary: Uses gpg --verify for full OpenPGP packet verification
  • libgcrypt: Direct Ed25519 signature verification without GPG binary
Key requirements: Only Ed25519 signatures are supported. RSA/ECDSA signatures will cause verification to fail.
Signature formats:
GPG binary dependency: Functions using GPG binary require gpg in PATH. libgcrypt-based verification works without GPG binary installed.
Key trust: GPG binary verification checks key trust and validity. libgcrypt verification only checks cryptographic signature validity.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides known hosts management functionality similar to SSH's known_hosts. Tracks server identity keys to detect man-in-the-middle attacks and key changes.

Known hosts file format:

  • Identity key entries: <IP:port> x25519 <hex_key> [comment]
  • No-identity entries: <IP:port> no-identity [comment]
Note
File format examples:
  • IPv4: 192.0.2.1:8080 x25519 1234abcd... ascii-chat
  • IPv6: [2001:db8::1]:8080 x25519 1234abcd... ascii-chat
  • No-identity: 192.0.2.1:8080 no-identity
No-identity servers: Servers without identity keys use "no-identity" entries. Cannot verify key (ephemeral keys change each connection) but can track server identity.
Key comparison: Uses constant-time comparison (sodium_memcmp) to prevent timing attacks.
MITM detection: Detects key mismatches by comparing received key with stored key. If key doesn't match, displays warning and prompts user for confirmation.
Multiple entries: Can have multiple entries for same IP:port (e.g., key rotation). Function searches all entries and uses first matching key.
Zero key handling: Special case for no-identity servers with zero keys. Zero key matches zero key (secure no-identity connection previously accepted).
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This file contains BearSSL tools utilities adapted to work with in-memory PEM data instead of files. Original code from BearSSL tools (ISC license).

These utilities are used for loading system CA certificates for TLS validation.

Note
BearSSL adaptation: Original BearSSL tools read PEM data from files. This version works with in-memory PEM data for better flexibility.
Trust anchors: Trust anchors are root CA certificates used for TLS validation. Loaded from system CA certificate store and used to validate server certificates.
Memory management: Trust anchors contain dynamically allocated memory. Must call free_ta_contents() for each anchor and free anchor_list.buf.
Author
Thomas Pornin (original BearSSL tools)
Zachary Fogg me@zf.nosp@m.o.gg (adaptation for ascii-chat)
Date
October 2025

This header provides SSH agent integration for signing operations. Allows keys to stay in SSH agent (not loaded into memory) for better security.

Note
SSH agent: Uses SSH agent protocol to communicate with ssh-agent. Keys stay in agent and are never loaded into application memory.
Platform support:
  • Unix: Uses SSH_AUTH_SOCK environment variable (Unix domain socket)
  • Windows: Uses SSH_AUTH_SOCK environment variable (named pipe)
Key format: Only Ed25519 keys are supported. RSA/ECDSA keys are NOT supported.
Agent detection: Checks SSH_AUTH_SOCK environment variable. On Unix, also verifies socket is accessible. On Windows, only checks environment variable (named pipes handled differently).
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

Macro Definition Documentation

◆ ANCHOR_LIST_INIT

#define ANCHOR_LIST_INIT   {NULL, 0, 0}

#include <include/ascii-chat/crypto/pem.h>

Initializer for anchor_list.

Macro for initializing an empty anchor_list structure. Sets all fields to zero/NULL.

Definition at line 103 of file pem.h.

Referenced by https_get().

◆ CRYPTO_FINGERPRINT_SIZE

#define CRYPTO_FINGERPRINT_SIZE   32

#include <include/ascii-chat/crypto/crypto.h>

Ed25519 key fingerprint size in bytes.

SHA-256 hash of the key, resulting in 32 bytes.

Definition at line 257 of file include/ascii-chat/crypto/crypto.h.

◆ CRYPTO_HEX_KEY64_SIZE

#define CRYPTO_HEX_KEY64_SIZE   128

#include <include/ascii-chat/crypto/crypto.h>

Hex string size for 64-byte key (128 hex characters).

Definition at line 273 of file include/ascii-chat/crypto/crypto.h.

◆ CRYPTO_HEX_KEY64_SIZE_NULL

#define CRYPTO_HEX_KEY64_SIZE_NULL   129

#include <include/ascii-chat/crypto/crypto.h>

Hex string size for 64-byte key with null terminator (129 bytes).

Definition at line 275 of file include/ascii-chat/crypto/crypto.h.

◆ CRYPTO_HEX_KEY_SIZE

#define CRYPTO_HEX_KEY_SIZE   64

#include <include/ascii-chat/crypto/crypto.h>

Hex string size for 32-byte key (64 hex characters).

Definition at line 269 of file include/ascii-chat/crypto/crypto.h.

Referenced by add_known_host(), and compute_key_fingerprint().

◆ CRYPTO_HEX_KEY_SIZE_NULL

#define CRYPTO_HEX_KEY_SIZE_NULL   65

#include <include/ascii-chat/crypto/crypto.h>

Hex string size for 32-byte key with null terminator (65 bytes).

Definition at line 271 of file include/ascii-chat/crypto/crypto.h.

Referenced by add_known_host(), compute_key_fingerprint(), and prompt_unknown_host().

◆ CRYPTO_KEY_SIZE

#define CRYPTO_KEY_SIZE   32

#include <include/ascii-chat/crypto/crypto.h>

Ed25519 key size in bytes.

Ed25519 public and private keys are 32 bytes each.

Definition at line 248 of file include/ascii-chat/crypto/crypto.h.

◆ CRYPTO_MAX_CIPHERTEXT_SIZE

#define CRYPTO_MAX_CIPHERTEXT_SIZE   (CRYPTO_MAX_PLAINTEXT_SIZE + CRYPTO_MAC_SIZE)

#include <include/ascii-chat/crypto/crypto.h>

Maximum ciphertext size (plaintext + MAC, ~1MB + 16 bytes).

Definition at line 87 of file include/ascii-chat/crypto/crypto.h.

◆ CRYPTO_MAX_PLAINTEXT_SIZE

#define CRYPTO_MAX_PLAINTEXT_SIZE   ((size_t)1024 * 1024)

◆ NO_IDENTITY_MARKER

#define NO_IDENTITY_MARKER   "no-identity"

#include <include/ascii-chat/crypto/crypto.h>

No-identity entry marker ("no-identity").

Definition at line 293 of file include/ascii-chat/crypto/crypto.h.

Referenced by add_known_host(), and check_known_host_with_key().

◆ OPENPGP_ALGO_ECDH

#define OPENPGP_ALGO_ECDH   18

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP algorithm ID for ECDH (Curve25519).

Definition at line 64 of file openpgp.h.

◆ OPENPGP_ALGO_EDDSA

#define OPENPGP_ALGO_EDDSA   22

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP algorithm ID for EdDSA (Ed25519).

Definition at line 61 of file openpgp.h.

Referenced by openpgp_parse_public_key_packet(), and openpgp_parse_secret_key_packet().

◆ OPENPGP_TAG_PUBLIC_KEY

#define OPENPGP_TAG_PUBLIC_KEY   6

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP packet tag for Public Key Packet.

Definition at line 49 of file openpgp.h.

Referenced by openpgp_parse_binary_pubkey().

◆ OPENPGP_TAG_SECRET_KEY

#define OPENPGP_TAG_SECRET_KEY   5

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP packet tag for Secret Key Packet.

Definition at line 52 of file openpgp.h.

Referenced by openpgp_parse_armored_seckey(), and openpgp_parse_binary_seckey().

◆ OPENPGP_TAG_SIGNATURE

#define OPENPGP_TAG_SIGNATURE   2

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP packet tag for Signature Packet.

Definition at line 58 of file openpgp.h.

◆ OPENPGP_TAG_USER_ID

#define OPENPGP_TAG_USER_ID   13

#include <include/ascii-chat/crypto/gpg/openpgp.h>

OpenPGP packet tag for User ID Packet.

Definition at line 55 of file openpgp.h.

◆ REKEY_DEFAULT_PACKET_THRESHOLD

#define REKEY_DEFAULT_PACKET_THRESHOLD   1000000

#include <include/ascii-chat/crypto/crypto.h>

Default rekey packet threshold (1 million packets).

Definition at line 1102 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_init().

◆ REKEY_DEFAULT_TIME_THRESHOLD

#define REKEY_DEFAULT_TIME_THRESHOLD   (3600LL * NS_PER_SEC_INT)

#include <include/ascii-chat/crypto/crypto.h>

Default rekey time threshold (1 hour in nanoseconds).

Definition at line 1100 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_init().

◆ REKEY_MAX_FAILURE_COUNT

#define REKEY_MAX_FAILURE_COUNT   10

#include <include/ascii-chat/crypto/crypto.h>

Maximum consecutive rekey failures before giving up.

Definition at line 1108 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_rekey_init().

◆ REKEY_MIN_INTERVAL

#define REKEY_MIN_INTERVAL   (3LL * NS_PER_SEC_INT)

#include <include/ascii-chat/crypto/crypto.h>

Minimum time interval between rekey requests (3 seconds in nanoseconds for testing, 60 for production).

Definition at line 1098 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_rekey_init().

◆ REKEY_MIN_REQUEST_INTERVAL

#define REKEY_MIN_REQUEST_INTERVAL   (60LL * NS_PER_SEC_INT)

#include <include/ascii-chat/crypto/crypto.h>

Minimum interval between rekey requests (60 seconds in nanoseconds, DDoS protection).

Definition at line 1110 of file include/ascii-chat/crypto/crypto.h.

◆ REKEY_TEST_PACKET_THRESHOLD

#define REKEY_TEST_PACKET_THRESHOLD   1000

#include <include/ascii-chat/crypto/crypto.h>

Test mode rekey packet threshold (1000 packets).

Definition at line 1106 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_init().

◆ REKEY_TEST_TIME_THRESHOLD

#define REKEY_TEST_TIME_THRESHOLD   (30LL * NS_PER_SEC_INT)

#include <include/ascii-chat/crypto/crypto.h>

Test mode rekey time threshold (30 seconds in nanoseconds).

Definition at line 1104 of file include/ascii-chat/crypto/crypto.h.

Referenced by crypto_init().

◆ SSH_ED25519_KEY_TYPE

#define SSH_ED25519_KEY_TYPE   "ssh-ed25519"

#include <include/ascii-chat/crypto/crypto.h>

SSH Ed25519 key type string ("ssh-ed25519").

Definition at line 289 of file include/ascii-chat/crypto/crypto.h.

◆ SSH_KEY_HEADER_SIZE

◆ SSH_KEY_PERMISSIONS_MASK

#define SSH_KEY_PERMISSIONS_MASK   (S_IRWXG | S_IRWXO)

◆ SSH_KEY_PUBLIC_KEY_LENGTH_SIZE

#define SSH_KEY_PUBLIC_KEY_LENGTH_SIZE   4

◆ SSH_KEY_PUBLIC_KEY_SIZE

#define SSH_KEY_PUBLIC_KEY_SIZE   32

◆ SSH_KEY_RECOMMENDED_PERMISSIONS

#define SSH_KEY_RECOMMENDED_PERMISSIONS   0600

◆ SSH_KEY_TYPE_LENGTH_SIZE

#define SSH_KEY_TYPE_LENGTH_SIZE   4

◆ SSH_KEY_TYPE_STRING_SIZE

#define SSH_KEY_TYPE_STRING_SIZE   11

◆ X25519_KEY_TYPE

#define X25519_KEY_TYPE   "x25519"

#include <include/ascii-chat/crypto/crypto.h>

X25519 key type string ("x25519").

Definition at line 291 of file include/ascii-chat/crypto/crypto.h.

Referenced by add_known_host().

Typedef Documentation

◆ crypto_context_t

typedef struct crypto_context_t crypto_context_t

#include <include/ascii-chat/crypto/crypto.h>

Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.

The context owns ephemeral X25519 material, the derived shared and optional password keys, negotiated wire sizes, authentication nonces, packet counters, and temporary keys during a rotation. Transports borrow it when sealing or opening packets. It is initialized through the crypto API and destroyed with crypto_destroy() so secret fields are wiped rather than copied or freed by callers.

Note
Nonce generation: Nonces are constructed as session_id || counter where session_id is 16 bytes and counter fills the remaining bytes. This construction aims to avoid nonce reuse, not to detect replays.
Session ID: Randomly generated for each connection and again on rekey. It contributes to nonce uniqueness; the decryptor does not check it.
Nonce counter: Starts at 1 (0 is reserved for testing) and increments for each encryption operation. Prevents nonce reuse within a session.
Byte order: Client must convert network byte order to host byte order for crypto parameters. Server uses host byte order directly.
Key exchange formats:
  • Simple format: Only ephemeral public key (when server has no identity key)
  • Authenticated format: Ephemeral key + identity key + signature (when server has identity key)

Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.

The context owns ephemeral X25519 material, the derived shared and optional password keys, negotiated wire sizes, authentication nonces, packet counters, and temporary keys during a rotation. Transports borrow it when sealing or opening packets. It must be initialized through the crypto API and destroyed through crypto_destroy() so secret fields are wiped rather than copied or freed by callers.

Enumeration Type Documentation

◆ crypto_result_t

#include <include/ascii-chat/crypto/crypto.h>

Cryptographic operation result codes.

Enumerator
CRYPTO_OK 

Operation succeeded

CRYPTO_ERROR_INIT_FAILED 

Initialization failed

CRYPTO_ERROR_INVALID_PARAMS 

Invalid parameters provided

CRYPTO_ERROR_MEMORY 

Memory allocation failed

CRYPTO_ERROR_LIBSODIUM 

libsodium operation failed

CRYPTO_ERROR_KEY_GENERATION 

Key generation failed

CRYPTO_ERROR_PASSWORD_DERIVATION 

Password-based key derivation failed

CRYPTO_ERROR_ENCRYPTION 

Encryption operation failed

CRYPTO_ERROR_DECRYPTION 

Decryption operation failed

CRYPTO_ERROR_INVALID_MAC 

MAC verification failed (possible tampering)

CRYPTO_ERROR_BUFFER_TOO_SMALL 

Output buffer too small

CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE 

Key exchange not complete

CRYPTO_ERROR_NONCE_EXHAUSTED 

Nonce counter exhausted (should rekey)

CRYPTO_ERROR_REKEY_IN_PROGRESS 

Rekey already in progress

CRYPTO_ERROR_REKEY_FAILED 

Rekey handshake failed

CRYPTO_ERROR_REKEY_RATE_LIMITED 

Too many rekey attempts (DDoS protection)

Definition at line 207 of file include/ascii-chat/crypto/crypto.h.

207 {
208 CRYPTO_OK = 0,
crypto_result_t
Cryptographic operation result codes.

Function Documentation

◆ add_known_host()

asciichat_error_t add_known_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[32] )

#include <include/ascii-chat/crypto/known_hosts.h>

Add server to known_hosts.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
server_keyServer's Ed25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Adds server identity key to known_hosts file. Creates file if it doesn't exist and creates directory if needed.

Note
File format: Adds entry as <IP:port> x25519 <hex_key> [comment]. Uses proper bracket notation for IPv6 addresses.
File creation: Creates ~/.ascii-chat/known_hosts if it doesn't exist. Creates ~/.ascii-chat/ directory if needed.
File permissions: Sets file permissions to 0600 (Unix only). Windows does not have Unix-style permissions.
Append mode: Appends entry to end of file (does not overwrite existing entries). Multiple entries for same IP:port are allowed (e.g., key rotation).
Key format: Converts server key to hex string (64 hex chars) for storage. Key is stored as X25519 format (32 bytes).
Warning
File permissions: Sets restrictive permissions (0600) but function may fail if file was just created by fopen (chmod may fail). This is acceptable.

References ED25519_PUBLIC_KEY_SIZE.

◆ check_known_host()

asciichat_error_t check_known_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[32] )

#include <include/ascii-chat/crypto/known_hosts.h>

Check if server key is in known_hosts.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
server_keyServer's Ed25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK if server not in known_hosts (first connection), positive value if key matches (connection verified), ERROR_CRYPTO_VERIFICATION if key mismatch (MITM warning)

Checks if server key matches known hosts entry for the given IP:port. Returns different values based on verification result.

Note
Return values:
  • ASCIICHAT_OK (0): Server not in known_hosts (first connection, needs verification)
  • Positive value (1): Key matches known_hosts (connection verified, safe to proceed)
  • ERROR_CRYPTO_VERIFICATION: Key mismatch (MITM attack or key rotation, needs user confirmation)
File format: Searches for entries matching <IP:port> x25519 <hex_key>. Supports both IPv4 and IPv6 addresses with proper bracket notation.
Multiple entries: If multiple entries exist for same IP:port, searches all entries and uses first matching key. Continues searching if key doesn't match.
No-identity entries: Skips "no-identity" entries when checking identity keys. If server has identity key but entry is "no-identity", continues searching.
Zero key handling: Special case for no-identity servers with zero keys. If both server key and stored key are zero, returns match (verified no-identity connection).
Key comparison: Uses constant-time comparison (sodium_memcmp) to prevent timing attacks.
File location: Uses ~/.ascii-chat/known_hosts (or equivalent on Windows). Returns ASCIICHAT_OK if file doesn't exist (first connection).
Warning
This function should NOT be called for servers without identity keys. Use check_known_host_no_identity() for servers without identity keys.
Key mismatch: Returns ERROR_CRYPTO_VERIFICATION if key doesn't match. This indicates potential MITM attack or key rotation. User should verify.

References ED25519_PUBLIC_KEY_SIZE.

◆ check_known_host_no_identity()

asciichat_error_t check_known_host_no_identity ( const char * server_ip,
uint16_t port )

#include <include/ascii-chat/crypto/known_hosts.h>

Check known_hosts for servers without identity key (no-identity entries).

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
Returns
ASCIICHAT_OK if server not in known_hosts (first connection), positive value if no-identity entry found (connection previously accepted), ERROR_CRYPTO_VERIFICATION if server previously had identity key but now has none

Checks if server has "no-identity" entry in known_hosts. Used for servers that don't have identity keys (ephemeral keys only).

Note
Return values:
  • ASCIICHAT_OK (0): Server not in known_hosts (first connection, needs verification)
  • Positive value (1): No-identity entry found (connection previously accepted)
  • ERROR_CRYPTO_VERIFICATION: Server previously had identity key but now has none (security concern)
File format: Searches for entries matching <IP:port> no-identity. Does NOT verify keys (no keys to verify for no-identity servers).
Purpose: This function is NOT for key verification (no keys to verify). Use check_known_host() for servers with identity keys.
Security: Cannot verify server identity (no identity key to verify). Only tracks whether user previously accepted connection to this server.
Warning
This function should NOT be used for key verification. Use check_known_host() for servers with identity keys.
Security limitation: Cannot verify server identity (no keys to compare). Only provides tracking of previously accepted connections.

Definition at line 265 of file known_hosts.c.

266 {
267 const char *path = get_known_hosts_path();
268 int fd = platform_open("known_hosts_file", path, PLATFORM_O_RDONLY,
269 FILE_PERM_PRIVATE);
270 if (fd < 0) {
271 // File doesn't exist - this is an unknown host that needs verification
272 log_warn("Known hosts file does not exist: %s", path);
273 return ASCIICHAT_OK; // Return 0 to indicate unknown host (first connection)
274 }
275
276 FILE *f = platform_fdopen("known_hosts_stream", fd, "r");
277 defer(SAFE_FCLOSE(f));
278 if (!f) {
279 // Failed to open file descriptor as FILE*
280 platform_close(fd);
281 log_warn("Failed to open known hosts file: %s", path);
282 return ASCIICHAT_OK; // Return 0 to indicate unknown host (first connection)
283 }
284
285 char line[BUFFER_SIZE_XLARGE];
286 char expected_prefix[BUFFER_SIZE_MEDIUM];
287
288 // Format IP:port with proper bracket notation for IPv6
289 char ip_with_port[BUFFER_SIZE_MEDIUM];
290 if (format_ip_with_port(server_ip, port, ip_with_port,
291 sizeof(ip_with_port)) != ASCIICHAT_OK) {
292
293 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
294 }
295
296 // Add space after IP:port for prefix matching
297 safe_snprintf(expected_prefix, sizeof(expected_prefix), "%s ", ip_with_port);
298
299 while (fgets(line, sizeof(line), f)) {
300 if (line[0] == '#')
301 continue; // Comment
302
303 // Use regex to parse and extract known_hosts line components
304 char *parsed_ip_port = NULL, *parsed_key_type = NULL,
305 *parsed_hex_key = NULL, *parsed_comment = NULL;
306 if (!crypto_regex_match_known_hosts(line, &parsed_ip_port, &parsed_key_type,
307 &parsed_hex_key, &parsed_comment)) {
308 continue; // Line doesn't match known_hosts format
309 }
310 defer(SAFE_FREE(parsed_comment));
311 defer(SAFE_FREE(parsed_hex_key));
312 defer(SAFE_FREE(parsed_key_type));
313 defer(SAFE_FREE(parsed_ip_port));
314
315 // Check if IP:port matches what we're looking for (with IPv6 normalization)
316 if (!compare_ip_port_strings(parsed_ip_port, ip_with_port)) {
317 continue; // Different IP:port
318 }
319
320 // Found matching IP:port - check key type
321 if (strcmp(parsed_key_type, "no-identity") == 0) {
322 // This is a server without identity key that was previously accepted by
323 // the user No warnings or user confirmation needed - user already
324 // accepted this server
325 return 1; // Known host (no-identity entry) - secure connection
326 }
327
328 // If we found a normal identity key entry, this is a mismatch
329 // Server previously had identity key but now has none
330 NOTICE(DANGER, "SERVER IDENTITY REMOVED",
331 "Server previously had identity key but now has none - potential "
332 "security issue");
333 return ERROR_CRYPTO_VERIFICATION; // Mismatch - server changed from identity
334 // to no-identity
335 }
336
337 return ASCIICHAT_OK; // Not found = first connection
338}
#define SET_ERRNO(code,...)
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
int platform_close(int fd)
Definition filesystem.c:91
#define BUFFER_SIZE_XLARGE
Extra large buffer size (2048 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define SAFE_FREE(ptr)
#define SAFE_FCLOSE(fp)
const char * get_known_hosts_path(void)
Get the path to the known_hosts file.
Definition known_hosts.c:59
@ ERROR_CRYPTO_VERIFICATION
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
asciichat_error_t format_ip_with_port(const char *ip, uint16_t port, char *output, size_t output_size)
Format IP address with port number.
Definition ip.c:180
int compare_ip_port_strings(const char *ip_port1, const char *ip_port2)
Compare two "IP:port" strings with IPv6 normalization.
Definition ip.c:1091
#define NOTICE(severity, title,...)
Definition notice.h:86
bool crypto_regex_match_known_hosts(const char *line, char **ip_port_out, char **key_type_out, char **hex_key_out, char **comment_out)
Definition regex.c:147

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, BUFFER_SIZE_XLARGE, compare_ip_port_strings(), crypto_regex_match_known_hosts(), ERROR_CRYPTO_VERIFICATION, ERROR_INVALID_PARAM, format_ip_with_port(), get_known_hosts_path(), log_warn, NOTICE, platform_close(), platform_open(), SAFE_FCLOSE, SAFE_FREE, and SET_ERRNO.

Referenced by crypto_handshake_client_key_exchange().

◆ check_known_host_with_key()

asciichat_error_t check_known_host_with_key ( const char * server_ip,
uint16_t port,
const uint8_t server_key[32],
uint8_t expected_key[32],
bool * has_expected_key )

#include <include/ascii-chat/crypto/known_hosts.h>

Same trust decision; optionally return the first stored nonzero identity for diagnostics. A mismatch can have multiple stored candidates. No fabricated key is returned for no-identity entries.

References ED25519_PUBLIC_KEY_SIZE.

◆ compute_key_fingerprint()

void compute_key_fingerprint ( const uint8_t key[32],
char fingerprint[(32 *2+1)] )

#include <include/ascii-chat/crypto/known_hosts.h>

Compute SHA256 fingerprint of Ed25519 key for display.

Parameters
keyEd25519 public key (32 bytes, must not be NULL)
fingerprintOutput buffer for fingerprint (65 bytes including null terminator)

Computes SHA256 fingerprint of Ed25519 public key for display. Fingerprint is displayed in hex format (64 hex chars + null terminator).

Note
Fingerprint format: SHA256 hash of key, displayed as 64 hex characters. Example: "a1b2c3d4e5f6..."
Output format: Fingerprint is stored as null-terminated hex string (65 bytes total). First 64 bytes are hex characters, 65th byte is null terminator.
Key format: Accepts Ed25519 public key (32 bytes). Fingerprint is computed over raw key bytes.
Use case: Used for displaying key fingerprints in warnings and prompts. Helps users verify keys visually.
Warning
Output buffer must be at least 65 bytes (64 hex chars + null terminator). Function does not validate buffer size (may overflow).

References ED25519_PUBLIC_KEY_SIZE, and HEX_STRING_SIZE_32.

◆ crypto_combine_auth_data()

void crypto_combine_auth_data ( const uint8_t * hmac,
const uint8_t * challenge_nonce,
uint8_t * combined_out )

#include <include/ascii-chat/crypto/crypto.h>

Combine HMAC and challenge nonce for transmission.

Parameters
hmacHMAC to transmit (32 bytes)
challenge_nonceChallenge nonce to transmit (32 bytes)
combined_outOutput buffer for combined data (64 bytes)

Combines HMAC and challenge nonce into a single buffer: [HMAC:32][nonce:32] Used to pack authentication response data for transmission.

Note
Format: [HMAC:32][challenge_nonce:32] (64 bytes total)

Definition at line 1312 of file lib/crypto/crypto.c.

1314 {
1315 if (!hmac || !challenge_nonce || !combined_out) {
1316 SET_ERRNO(
1318 "Invalid parameters: hmac=%p, challenge_nonce=%p, combined_out=%p",
1319 hmac, challenge_nonce, combined_out);
1320 return;
1321 }
1322
1323 // Combine HMAC (32 bytes) + challenge nonce (32 bytes) = 64 bytes total
1324 memcpy(combined_out, hmac, HMAC_SHA256_SIZE);
1325 memcpy(combined_out + AUTH_HMAC_SIZE, challenge_nonce, AUTH_CHALLENGE_SIZE);
1326}
#define AUTH_CHALLENGE_SIZE
Challenge nonce size (32 bytes).
Definition sizes.h:104
#define HMAC_SHA256_SIZE
HMAC-SHA256 output size in bytes.
Definition sizes.h:48
#define AUTH_HMAC_SIZE
HMAC size in authentication packets (32 bytes).
Definition sizes.h:102

References AUTH_CHALLENGE_SIZE, AUTH_HMAC_SIZE, ERROR_INVALID_PARAM, HMAC_SHA256_SIZE, and SET_ERRNO.

◆ crypto_compute_auth_response()

crypto_result_t crypto_compute_auth_response ( const crypto_context_t * ctx,
const uint8_t nonce[32],
uint8_t hmac_out[32] )

#include <include/ascii-chat/crypto/crypto.h>

Compute authentication response HMAC bound to DH shared_secret.

Parameters
ctxCrypto context with keys (must have completed key exchange)
nonceChallenge nonce from server (32 bytes)
hmac_outOutput HMAC (32 bytes)
Returns
CRYPTO_OK on success, error code on failure

Computes: HMAC(auth_key, nonce || shared_secret) This binds the password/key authentication to the DH exchange, preventing MITM.

Note
Key selection: Uses password_key if available, otherwise uses shared_key. This allows password authentication to be optional while still binding to DH.
Key exchange requirement: ctx->key_exchange_complete must be true. Returns CRYPTO_ERROR_INVALID_PARAMS if key exchange is not complete.
MITM prevention: By including shared_secret in the HMAC computation, an attacker cannot intercept and replay authentication responses without knowing the shared secret.
Warning
Context must have completed key exchange before calling this function.

References AUTH_CHALLENGE_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_compute_hmac()

crypto_result_t crypto_compute_hmac ( crypto_context_t * ctx,
const uint8_t key[32],
const uint8_t data[32],
uint8_t hmac[32] )

#include <include/ascii-chat/crypto/crypto.h>

Compute HMAC-SHA256 for fixed 32-byte data.

Parameters
ctxCrypto context (for libsodium initialization check)
keyHMAC key (32 bytes)
dataData to authenticate (32 bytes)
hmacOutput buffer for HMAC (32 bytes)
Returns
CRYPTO_OK on success, error code on failure

Computes HMAC-SHA256 over exactly 32 bytes of data. Useful for authenticating challenge nonces and other fixed-size values.

Note
Automatically initializes libsodium if not already initialized.

References AUTH_CHALLENGE_SIZE, HMAC_SHA256_KEY_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_compute_hmac_ex()

crypto_result_t crypto_compute_hmac_ex ( const crypto_context_t * ctx,
const uint8_t key[32],
const uint8_t * data,
size_t data_len,
uint8_t hmac[32] )

#include <include/ascii-chat/crypto/crypto.h>

Compute HMAC-SHA256 for variable-length data.

Parameters
ctxCrypto context (for libsodium initialization check)
keyHMAC key (32 bytes)
dataData to authenticate (variable length)
data_lenLength of data (must be > 0)
hmacOutput buffer for HMAC (32 bytes)
Returns
CRYPTO_OK on success, error code on failure

Computes HMAC-SHA256 over variable-length data. Useful for authenticating combined values (e.g., nonce || shared_secret).

Note
Automatically initializes libsodium if not already initialized.

References HMAC_SHA256_KEY_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_compute_password_hmac()

asciichat_error_t crypto_compute_password_hmac ( crypto_context_t * ctx,
const uint8_t * password_key,
const uint8_t * nonce,
const uint8_t * shared_secret,
uint8_t * hmac_out )

#include <include/ascii-chat/crypto/crypto.h>

Compute password-based HMAC for authentication.

Parameters
ctxCrypto context
password_keyPassword-derived key (32 bytes)
nonceChallenge nonce (32 bytes)
shared_secretDH shared secret (32 bytes)
hmac_outOutput buffer for HMAC (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Computes: HMAC(password_key, nonce || shared_secret) Binds password authentication to DH key exchange, preventing MITM.

Note
Used by authentication handlers to prove knowledge of password AND shared secret.
Combined data: nonce || shared_secret (64 bytes total)

Definition at line 1223 of file lib/crypto/crypto.c.

1227 {
1228 if (!ctx || !password_key || !nonce || !shared_secret || !hmac_out) {
1230 "Invalid parameters: ctx=%p, password_key=%p, nonce=%p, "
1231 "shared_secret=%p, hmac_out=%p",
1232 ctx, password_key, nonce, shared_secret, hmac_out);
1233 }
1234
1235 // Combine nonce and shared_secret for HMAC computation
1236 // This binds the password to the DH shared secret, preventing MITM attacks
1238 memcpy(combined_data, nonce, AUTH_CHALLENGE_SIZE);
1239 memcpy(combined_data + AUTH_CHALLENGE_SIZE, shared_secret,
1241
1242 // Compute HMAC using the password-derived key
1243 if (crypto_compute_hmac_ex(ctx, password_key, combined_data, 64, hmac_out) !=
1244 0) {
1245 // Securely zero sensitive data containing shared secret even on error
1246 sodium_memzero(combined_data, sizeof(combined_data));
1247 return SET_ERRNO(ERROR_CRYPTO, "Failed to compute password HMAC");
1248 }
1249
1250 // Securely zero sensitive data containing shared secret
1251 sodium_memzero(combined_data, sizeof(combined_data));
1252
1253 return ASCIICHAT_OK;
1254}
unsigned char uint8_t
@ ERROR_CRYPTO
crypto_result_t crypto_compute_hmac_ex(const crypto_context_t *ctx, const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t *data, size_t data_len, uint8_t hmac[HMAC_SHA256_SIZE])
#define CRYPTO_SHARED_KEY_SIZE
Shared key size (X25519).
Definition sizes.h:76

References ASCIICHAT_OK, AUTH_CHALLENGE_SIZE, crypto_compute_hmac_ex(), CRYPTO_SHARED_KEY_SIZE, ERROR_CRYPTO, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ crypto_create_auth_challenge()

crypto_result_t crypto_create_auth_challenge ( crypto_context_t * ctx,
uint8_t * packet_out,
size_t packet_size,
size_t * packet_len_out )

#include <include/ascii-chat/crypto/crypto.h>

Create authentication challenge packet.

Parameters
ctxCrypto context (must be initialized)
packet_outOutput buffer for challenge packet
packet_sizeSize of output buffer
packet_len_outOutput parameter for actual packet length
Returns
CRYPTO_OK on success, error code on failure

Creates an authentication challenge packet: [type:4][nonce:auth_challenge_size] Generates a random nonce and stores it in ctx->auth_nonce for later verification.

Note
Packet format: [PACKET_TYPE_AUTH_CHALLENGE:4][random_nonce:32] Total size: sizeof(uint32_t) + ctx->auth_challenge_size (typically 36 bytes)
The generated nonce is stored in ctx->auth_nonce and should be used later to verify the authentication response.

Definition at line 1102 of file lib/crypto/crypto.c.

1105 {
1106 if (!ctx || !ctx->initialized || !packet_out || !packet_len_out) {
1108 "Invalid parameters (ctx=%p, initialized=%d, packet_out=%p, "
1109 "packet_len_out=%p)",
1110 ctx, ctx ? ctx->initialized : 0, packet_out, packet_len_out);
1112 }
1113
1114 size_t required_size =
1115 sizeof(uint32_t) + ctx->auth_challenge_size; // type + nonce
1116 if (packet_size < required_size) {
1117 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)",
1118 packet_size, required_size);
1120 }
1121
1122 // Generate random nonce (stores result in ctx->auth_nonce)
1124 if (result != CRYPTO_OK) {
1125 return result;
1126 }
1127
1128 // Pack packet: [type:4][nonce:auth_challenge_size]
1129 uint32_t packet_type = CRYPTO_PACKET_AUTH_CHALLENGE;
1130 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type,
1131 sizeof(packet_type));
1132 SAFE_MEMCPY(packet_out + sizeof(packet_type), ctx->auth_challenge_size,
1133 ctx->auth_nonce, ctx->auth_challenge_size);
1134
1135 *packet_len_out = required_size;
1136 return CRYPTO_OK;
1137}
unsigned int uint32_t
#define SAFE_MEMCPY(dest, dest_size, src, count)
@ ERROR_BUFFER
crypto_result_t crypto_generate_nonce(uint8_t nonce[AUTH_CHALLENGE_SIZE])

References crypto_context_t::auth_challenge_size, crypto_context_t::auth_nonce, CRYPTO_ERROR_BUFFER_TOO_SMALL, CRYPTO_ERROR_INVALID_PARAMS, crypto_generate_nonce(), CRYPTO_OK, ERROR_BUFFER, ERROR_INVALID_PARAM, crypto_context_t::initialized, SAFE_MEMCPY, and SET_ERRNO.

◆ crypto_create_encrypted_packet()

crypto_result_t crypto_create_encrypted_packet ( crypto_context_t * ctx,
const uint8_t * data,
size_t data_len,
uint8_t * packet_out,
size_t packet_size,
size_t * packet_len_out )

#include <include/ascii-chat/crypto/crypto.h>

Create encrypted data packet for network transmission.

Parameters
ctxCrypto context (must be initialized and ready)
dataPlaintext data to encrypt
data_lenLength of plaintext data
packet_outOutput buffer for encrypted packet
packet_sizeSize of output buffer
packet_len_outOutput parameter for actual packet length
Returns
CRYPTO_OK on success, error code on failure

Creates an encrypted data packet: [type:4][length:4][encrypted_data:var] Encrypts the data using crypto_encrypt() and prepends packet type and length.

Note
Packet format: [PACKET_TYPE_ENCRYPTED_DATA:4][data_length:4][encrypted_data] Encrypted data format: [nonce:24][encrypted_data][MAC:16] Total size: sizeof(uint32_t) + sizeof(uint32_t) + data_len + nonce_size + mac_size
Context must be ready (crypto_is_ready() returns true) before calling. This requires either completed key exchange or password-based encryption.
Warning
Ensure packet_size is large enough for encrypted data + headers.

Definition at line 804 of file lib/crypto/crypto.c.

806 {
807 if (!ctx || !data || !packet_out || !packet_len_out) {
809 "Invalid parameters (ctx=%p, data=%p, packet_out=%p, "
810 "packet_len_out=%p)",
811 ctx, data, packet_out, packet_len_out);
813 }
814
815 if (!crypto_is_ready(ctx)) {
816 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready");
818 }
819
820 // Validate data_len to prevent integer overflow in size calculations.
821 if (data_len > CRYPTO_MAX_PLAINTEXT_SIZE) {
822 SET_ERRNO(ERROR_INVALID_PARAM, "data_len %zu exceeds max %d", data_len,
825 }
826
827 // Check for integer overflow: data_len + nonce_size + mac_size
828 if (data_len > SIZE_MAX - ctx->nonce_size - ctx->mac_size) {
829 SET_ERRNO(ERROR_BUFFER, "encrypted_size overflow");
831 }
832 size_t encrypted_size = data_len + ctx->nonce_size + ctx->mac_size;
833
834 // Check for integer overflow: header + encrypted_size
835 size_t header_size = sizeof(uint32_t) + sizeof(uint32_t);
836 if (encrypted_size > SIZE_MAX - header_size) {
837 SET_ERRNO(ERROR_BUFFER, "required_size overflow");
839 }
840 size_t required_size =
841 header_size + encrypted_size; // type + len + encrypted_data
842
843 if (packet_size < required_size) {
844 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)",
845 packet_size, required_size);
847 }
848
849 // Encrypt the data
850 size_t ciphertext_len;
851 uint8_t *encrypted_data = packet_out + sizeof(uint32_t) + sizeof(uint32_t);
853 ctx, data, data_len, encrypted_data,
854 packet_size - sizeof(uint32_t) - sizeof(uint32_t), &ciphertext_len);
855 if (result != CRYPTO_OK) {
856 return result;
857 }
858
859 // Pack packet: [type:4][length:4][encrypted_data:var]
860 uint32_t packet_type = CRYPTO_PACKET_ENCRYPTED_DATA;
861 uint32_t data_length = (uint32_t)ciphertext_len;
862
863 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type,
864 sizeof(packet_type));
865 SAFE_MEMCPY(packet_out + sizeof(packet_type), sizeof(data_length),
866 &data_length, sizeof(data_length));
867
868 *packet_len_out = required_size;
869 return CRYPTO_OK;
870}
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.
bool crypto_is_ready(const crypto_context_t *ctx)
Check if key exchange is complete and ready for encryption.
#define CRYPTO_MAX_PLAINTEXT_SIZE
Maximum plaintext size (1MB).

References crypto_encrypt(), CRYPTO_ERROR_BUFFER_TOO_SMALL, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE, crypto_is_ready(), CRYPTO_MAX_PLAINTEXT_SIZE, CRYPTO_OK, ERROR_BUFFER, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::mac_size, crypto_context_t::nonce_size, SAFE_MEMCPY, and SET_ERRNO.

◆ crypto_create_public_key_packet()

crypto_result_t crypto_create_public_key_packet ( const crypto_context_t * ctx,
uint8_t * packet_out,
size_t packet_size,
size_t * packet_len_out )

#include <include/ascii-chat/crypto/crypto.h>

Create public key packet for network transmission.

Parameters
ctxCrypto context (must be initialized)
packet_outOutput buffer for packet
packet_sizeSize of output buffer
packet_len_outOutput parameter for actual packet length
Returns
CRYPTO_OK on success, error code on failure

Creates a public key packet: [type:4][public_key:public_key_size] Used during key exchange handshake to send ephemeral public key to peer.

Note
Packet format: [PACKET_TYPE_PUBLIC_KEY:4][ephemeral_public_key:32] Total size: sizeof(uint32_t) + ctx->public_key_size (typically 36 bytes)
This packet is NOT encrypted - it's part of the key exchange protocol.

Definition at line 737 of file lib/crypto/crypto.c.

740 {
741 if (!ctx || !ctx->initialized || !packet_out || !packet_len_out) {
743 "Invalid parameters (ctx=%p, initialized=%d, packet_out=%p, "
744 "packet_len_out=%p)",
745 ctx, ctx ? ctx->initialized : 0, packet_out, packet_len_out);
747 }
748
749 size_t required_size = sizeof(uint32_t) + ctx->public_key_size; // type + key
750 if (packet_size < required_size) {
751 SET_ERRNO(ERROR_BUFFER, "Buffer too small (size=%zu, required=%zu)",
752 packet_size, required_size);
754 }
755
756 // Pack packet: [type:4][public_key:32]
757 uint32_t packet_type = CRYPTO_PACKET_PUBLIC_KEY;
758 SAFE_MEMCPY(packet_out, sizeof(packet_type), &packet_type,
759 sizeof(packet_type));
760 // Bounds check to prevent buffer overflow
761 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE)
762 ? ctx->public_key_size
764 SAFE_MEMCPY(packet_out + sizeof(packet_type), copy_size, ctx->public_key,
765 copy_size);
766
767 *packet_len_out = required_size;
768 return CRYPTO_OK;
769}
#define X25519_KEY_SIZE
X25519 key size in bytes.
Definition sizes.h:36

References CRYPTO_ERROR_BUFFER_TOO_SMALL, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_BUFFER, ERROR_INVALID_PARAM, crypto_context_t::initialized, crypto_context_t::public_key, crypto_context_t::public_key_size, SAFE_MEMCPY, SET_ERRNO, and X25519_KEY_SIZE.

◆ crypto_decrypt()

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 )

#include <include/ascii-chat/crypto/crypto.h>

Decrypt data using XSalsa20-Poly1305.

Parameters
ctxCrypto context (must be initialized and ready)
ciphertextCiphertext data to decrypt
ciphertext_lenLength of ciphertext (must be >= nonce_size + mac_size)
plaintext_outOutput buffer for plaintext
plaintext_out_sizeSize of output buffer
plaintext_len_outOutput parameter for actual plaintext length
Returns
CRYPTO_OK on success, CRYPTO_ERROR_INVALID_MAC if MAC verification fails

Decrypts data using XSalsa20-Poly1305 authenticated encryption. Uses shared_key if key exchange is complete, otherwise falls back to password_key.

Note
Ciphertext format: [nonce:nonce_size][encrypted_data][MAC:mac_size] Nonce is extracted from the first nonce_size bytes of ciphertext.
MAC verification: Automatically verified during decryption. Returns CRYPTO_ERROR_INVALID_MAC if MAC verification fails (indicating tampering or wrong key).
Plaintext size: ciphertext_len - nonce_size - mac_size
Buffer requirements: plaintext_out_size must be >= ciphertext_len - nonce_size - mac_size
Warning
Context must be ready (crypto_is_ready() returns true) before calling this function.
Always check return value. CRYPTO_ERROR_INVALID_MAC indicates tampering or wrong key.

Definition at line 571 of file lib/crypto/crypto.c.

574 {
575 ASCII_OTEL_SCOPE(CRYPTO_DECRYPT);
576 ASCII_OTEL_ATTR_STRING("crypto.operation", "decrypt");
577 ASCII_OTEL_ATTR_STRING("crypto.algorithm", "xsalsa20-poly1305");
578 ASCII_OTEL_ATTR_INT("crypto.input.size", (int64_t)ciphertext_len);
579 ASCII_OTEL_ATTR_INT("crypto.output.capacity", (int64_t)plaintext_out_size);
580 if (!ctx || !ctx->initialized || !ciphertext || !plaintext_out ||
581 !plaintext_len_out) {
583 "Invalid parameters: ctx=%p, initialized=%d, ciphertext=%p, "
584 "plaintext_out=%p, plaintext_len_out=%p",
585 ctx, ctx ? ctx->initialized : 0, ciphertext, plaintext_out,
586 plaintext_len_out);
588 }
589
590 if (!crypto_is_ready(ctx)) {
591 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready for decryption");
593 }
594
595 ASCII_OTEL_ATTR_INT("crypto.nonce.size", ctx->nonce_size);
596 ASCII_OTEL_ATTR_INT("crypto.mac.size", ctx->mac_size);
597 ASCII_OTEL_ATTR_INT("crypto.key.size", ctx->encryption_key_size);
598 ASCII_OTEL_ATTR_STRING("crypto.key.source",
599 ctx->key_exchange_complete ? "x25519" : "password");
600 // Check minimum ciphertext size (nonce + MAC)
601 size_t min_ciphertext_size = ctx->nonce_size + ctx->mac_size;
602 if (ciphertext_len < min_ciphertext_size) {
603 SET_ERRNO(ERROR_INVALID_PARAM, "Ciphertext too small: %zu < %zu",
604 ciphertext_len, min_ciphertext_size);
606 }
607
608 size_t plaintext_len = ciphertext_len - ctx->nonce_size - ctx->mac_size;
609 if (plaintext_out_size < plaintext_len) {
610 SET_ERRNO(ERROR_BUFFER, "Plaintext buffer too small: %zu < %zu",
611 plaintext_out_size, plaintext_len);
613 }
614
615 // Extract nonce from beginning of ciphertext
616 const uint8_t *nonce = ciphertext;
617 const uint8_t *encrypted_data = ciphertext + ctx->nonce_size;
618
619 // Choose decryption key (prefer shared key over password key)
620 const uint8_t *decryption_key = NULL;
621 if (ctx->key_exchange_complete) {
622 decryption_key = ctx->shared_key;
623 } else if (ctx->has_password) {
624 decryption_key = ctx->password_key;
625 } else {
626 SET_ERRNO(ERROR_CRYPTO, "No decryption key available");
628 }
629
630 // Decrypt using NaCl secretbox (XSalsa20 + Poly1305)
631 if (crypto_secretbox_open_easy(plaintext_out, encrypted_data,
632 ciphertext_len - ctx->nonce_size, nonce,
633 decryption_key) != 0) {
635 "Decryption failed: cipherlen=%zu key_exchange_complete=%d "
636 "has_password=%d (invalid MAC)",
637 ciphertext_len - ctx->nonce_size,
640 "Decryption failed - invalid MAC or corrupted data");
642 }
643
644 *plaintext_len_out = plaintext_len;
645 ctx->bytes_decrypted += plaintext_len;
646
647 ASCII_OTEL_ATTR_INT("crypto.output.size", (int64_t)*plaintext_len_out);
648 ASCII_OTEL_ATTR_INT("crypto.authenticated", 1);
649 ascii_otel_metric(ASCII_OTEL_METRIC_CRYPTO_DECRYPT_BYTES,
650 (double)ciphertext_len);
651 return CRYPTO_OK;
652}
#define US_PER_SEC_INT
Definition time.h:177
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:94
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:92

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ascii_otel_metric(), ASCII_OTEL_SCOPE, crypto_context_t::bytes_decrypted, CRYPTO_ERROR_BUFFER_TOO_SMALL, CRYPTO_ERROR_INVALID_MAC, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE, crypto_is_ready(), CRYPTO_OK, crypto_context_t::encryption_key_size, ERROR_BUFFER, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_password, crypto_context_t::initialized, crypto_context_t::key_exchange_complete, log_error_every, crypto_context_t::mac_size, crypto_context_t::nonce_size, crypto_context_t::password_key, SET_ERRNO, crypto_context_t::shared_key, and US_PER_SEC_INT.

Referenced by crypto_process_encrypted_packet(), and crypto_record_open_sequence().

◆ crypto_derive_password_encryption_key()

crypto_result_t crypto_derive_password_encryption_key ( const char * password,
uint8_t encryption_key[32] )

#include <include/ascii-chat/crypto/crypto.h>

Derive deterministic encryption key from password for handshake.

Parameters
passwordPassword to derive key from
encryption_keyOutput buffer for derived key (CRYPTO_ENCRYPTION_KEY_SIZE bytes)
Returns
CRYPTO_OK on success, error code on failure

Derives a deterministic key using a fixed salt (for handshake purposes). This allows password-protected sessions without requiring key exchange to be completed first.

Note
Uses same deterministic salt ("ascii-chat-password-salt-v1") as crypto_derive_password_key() for consistency.
Same password always produces same key. Only use for handshake encryption, not for long-term key storage.

References buffer_size, and CRYPTO_ENCRYPTION_KEY_SIZE.

◆ crypto_derive_password_key()

crypto_result_t crypto_derive_password_key ( crypto_context_t * ctx,
const char * password )

#include <include/ascii-chat/crypto/crypto.h>

Derive key from password using Argon2id.

Parameters
ctxCrypto context (must be initialized)
passwordPassword to derive key from
Returns
CRYPTO_OK on success, error code on failure

Derives a 32-byte encryption key from the password using Argon2id KDF. The salt is deterministic ("ascii-chat-password-salt-v1") for consistent key derivation across client/server.

Note
Argon2id is memory-hard, making offline brute-force attacks expensive.
Salt: Uses deterministic salt ("ascii-chat-password-salt-v1") padded to ARGON2ID_SALT_SIZE (32 bytes) with zeros. This ensures the same password produces the same key on both client and server.
Argon2id parameters: Uses INTERACTIVE limits (~0.1 seconds, ~64MB memory).
Warning
Deterministic salt: Same password always produces same key. Only use for session encryption, not long-term key storage.

Definition at line 347 of file lib/crypto/crypto.c.

348 {
349 if (!ctx || !ctx->initialized || !password) {
351 "Invalid parameters (ctx=%p, initialized=%d, password=%p)", ctx,
352 ctx ? ctx->initialized : 0, password);
354 }
355
356 // Validate password length requirements
357 crypto_result_t validation_result = crypto_validate_password(password);
358 if (validation_result != CRYPTO_OK) {
359 return validation_result;
360 }
361
362 // Use deterministic salt for consistent key derivation across client/server
363 // This ensures the same password produces the same key on both sides
364 // Salt must be exactly ARGON2ID_SALT_SIZE (32) bytes
365 const char *deterministic_salt = "ascii-chat-password-salt-v1";
366 size_t salt_str_len = strlen(deterministic_salt);
367
368 // Zero-initialize the salt buffer first
369 memset(ctx->password_salt, 0, ctx->salt_size);
370
371 // Copy the salt string (will be padded with zeros to ctx->salt_size)
372 memcpy(ctx->password_salt, deterministic_salt,
373 (salt_str_len < ctx->salt_size) ? salt_str_len : ctx->salt_size);
374
375 // Derive key using Argon2id (memory-hard, secure against GPU attacks)
376 if (crypto_pwhash(ctx->password_key, ctx->encryption_key_size, password,
377 strlen(password), ctx->password_salt,
378 crypto_pwhash_OPSLIMIT_INTERACTIVE, // ~0.1 seconds
379 crypto_pwhash_MEMLIMIT_INTERACTIVE, // ~64MB
380 crypto_pwhash_ALG_DEFAULT) != 0) {
382 "Password key derivation failed - possibly out of memory");
384 }
385
386 log_dev("Password key derived successfully using Argon2id with deterministic "
387 "salt");
388 return CRYPTO_OK;
389}
crypto_result_t crypto_validate_password(const char *password)
Validate password length requirements.
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_PASSWORD_DERIVATION, CRYPTO_OK, crypto_validate_password(), crypto_context_t::encryption_key_size, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::initialized, log_dev, crypto_context_t::password_key, crypto_context_t::password_salt, crypto_context_t::salt_size, and SET_ERRNO.

Referenced by crypto_handshake_client_auth_response(), and crypto_init_with_password().

◆ crypto_destroy()

void crypto_destroy ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Cleanup crypto context with secure memory wiping.

Parameters
ctxCrypto context to cleanup

Securely zeroes all sensitive data (keys, salts, etc.) before freeing. Always call this when done with a crypto context.

Note
Uses sodium_memzero() to prevent key material from persisting in memory.

Definition at line 211 of file lib/crypto/crypto.c.

211 {
212 if (!ctx || !ctx->initialized) {
213 return;
214 }
215
217
218 // Securely wipe sensitive data
219 secure_memzero(ctx->private_key, sizeof(ctx->private_key));
220 secure_memzero(ctx->shared_key, sizeof(ctx->shared_key));
221 secure_memzero(ctx->password_key, sizeof(ctx->password_key));
222 secure_memzero(ctx->password_salt, sizeof(ctx->password_salt));
223
224 char encrypted_str[CRYPTO_ENCRYPTED_BUFFER_SIZE],
225 decrypted_str[CRYPTO_DECRYPTED_BUFFER_SIZE];
226 format_bytes_pretty(ctx->bytes_encrypted, encrypted_str,
227 sizeof(encrypted_str));
228 format_bytes_pretty(ctx->bytes_decrypted, decrypted_str,
229 sizeof(decrypted_str));
230
231 log_debug("Crypto context cleaned up (encrypted: %s, decrypted: %s)",
232 encrypted_str, decrypted_str);
233
234 // Clear entire context
235 secure_memzero(ctx, sizeof(crypto_context_t));
236}
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:12
#define CRYPTO_ENCRYPTED_BUFFER_SIZE
#define CRYPTO_DECRYPTED_BUFFER_SIZE
void crypto_session_destroy(crypto_context_t *crypto)
Endpoint cryptographic state for handshake, packet protection, authentication, and rekeying.

References crypto_context_t::bytes_decrypted, crypto_context_t::bytes_encrypted, CRYPTO_DECRYPTED_BUFFER_SIZE, CRYPTO_ENCRYPTED_BUFFER_SIZE, crypto_session_destroy(), format_bytes_pretty(), crypto_context_t::initialized, log_debug, crypto_context_t::password_key, crypto_context_t::password_salt, crypto_context_t::private_key, and crypto_context_t::shared_key.

Referenced by acip_transport_destroy(), crypto_handshake_destroy(), and crypto_init_with_password().

◆ crypto_encrypt()

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 )

#include <include/ascii-chat/crypto/crypto.h>

Encrypt data using XSalsa20-Poly1305.

Parameters
ctxCrypto context (must be initialized and ready)
plaintextPlaintext data to encrypt
plaintext_lenLength of plaintext (must be > 0 and <= CRYPTO_MAX_PLAINTEXT_SIZE)
ciphertext_outOutput buffer for ciphertext
ciphertext_out_sizeSize of output buffer
ciphertext_len_outOutput parameter for actual ciphertext length
Returns
CRYPTO_OK on success, error code on failure

Encrypts data using XSalsa20-Poly1305 authenticated encryption. Uses shared_key if key exchange is complete, otherwise falls back to password_key.

Note
Nonce generation: Automatically generates nonce as session_id || counter. Nonce is prepended to ciphertext: [nonce:24][encrypted_data + MAC]. Counter increments after each encryption to prevent nonce reuse.
Ciphertext format: [nonce:nonce_size][encrypted_data][MAC:mac_size] Total size = plaintext_len + nonce_size + mac_size
Buffer requirements: ciphertext_out_size must be >= plaintext_len + nonce_size + mac_size
Nonce counter: Starts at 1 (0 reserved for testing). Returns CRYPTO_ERROR_NONCE_EXHAUSTED if counter reaches 0 or UINT64_MAX (extremely unlikely, but triggers rekeying).
Maximum plaintext size: CRYPTO_MAX_PLAINTEXT_SIZE (1MB)
Rekeying: Automatically increments rekey_packet_count. Check crypto_should_rekey() after encryption to determine if rekeying should be initiated.
Warning
Context must be ready (crypto_is_ready() returns true) before calling this function.

Definition at line 478 of file lib/crypto/crypto.c.

481 {
482 ASCII_OTEL_SCOPE(CRYPTO_ENCRYPT);
483 ASCII_OTEL_ATTR_STRING("crypto.operation", "encrypt");
484 ASCII_OTEL_ATTR_STRING("crypto.algorithm", "xsalsa20-poly1305");
485 ASCII_OTEL_ATTR_INT("crypto.input.size", (int64_t)plaintext_len);
486 ASCII_OTEL_ATTR_INT("crypto.output.capacity", (int64_t)ciphertext_out_size);
487 if (!ctx || !ctx->initialized || !plaintext || !ciphertext_out ||
488 !ciphertext_len_out) {
490 "Invalid parameters: ctx=%p, initialized=%d, plaintext=%p, "
491 "ciphertext_out=%p, ciphertext_len_out=%p",
492 ctx, ctx ? ctx->initialized : 0, plaintext, ciphertext_out,
493 ciphertext_len_out);
495 }
496
497 if (plaintext_len == 0 || plaintext_len > CRYPTO_MAX_PLAINTEXT_SIZE) {
498 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid plaintext length: %zu (max: %d)",
499 plaintext_len, CRYPTO_MAX_PLAINTEXT_SIZE);
501 }
502
503 if (!crypto_is_ready(ctx)) {
504 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready for encryption");
506 }
507
508 ASCII_OTEL_ATTR_INT("crypto.nonce.size", ctx->nonce_size);
509 ASCII_OTEL_ATTR_INT("crypto.mac.size", ctx->mac_size);
510 ASCII_OTEL_ATTR_INT("crypto.key.size", ctx->encryption_key_size);
511 ASCII_OTEL_ATTR_STRING("crypto.key.source",
512 ctx->key_exchange_complete ? "x25519" : "password");
513 // Check output buffer size
514 size_t required_size = plaintext_len + ctx->nonce_size + ctx->mac_size;
515 if (ciphertext_out_size < required_size) {
516 SET_ERRNO(ERROR_BUFFER, "Ciphertext buffer too small: %zu < %zu",
517 ciphertext_out_size, required_size);
519 }
520
521 // Check for nonce counter exhaustion (extremely unlikely in practice)
522 // Starting from 1, reaching UINT64_MAX would require ~292 billion years at 60
523 // FPS. With key rotation required at 1M packets (~16 seconds), exhaustion is
524 // virtually impossible. This check is a safety fallback that should never
525 // trigger in practice.
526 if (ctx->nonce_counter == 0 || ctx->nonce_counter == UINT64_MAX) {
527 SET_ERRNO(ERROR_CRYPTO, "Nonce counter exhausted - key rotation required");
529 }
530
531 // Choose encryption key BEFORE generating nonce (prevents nonce_counter
532 // increment on error)
533 const uint8_t *encryption_key = NULL;
534 if (ctx->key_exchange_complete) {
535 encryption_key = ctx->shared_key;
536 } else if (ctx->has_password) {
537 encryption_key = ctx->password_key;
538 } else {
539 SET_ERRNO(ERROR_CRYPTO, "No encryption key available");
541 }
542
543 // Generate nonce and place at beginning of ciphertext
544 uint8_t nonce[XSALSA20_NONCE_SIZE]; // Use maximum nonce size for buffer
545 generate_nonce(ctx, nonce);
546 SAFE_MEMCPY(ciphertext_out, ctx->nonce_size, nonce, ctx->nonce_size);
547
549 "Encrypting packet: counter=%llu plaintext_len=%zu",
550 (unsigned long long)(ctx->nonce_counter - 1), plaintext_len);
551
552 // Encrypt using NaCl secretbox (XSalsa20 + Poly1305)
553 if (crypto_secretbox_easy(ciphertext_out + ctx->nonce_size, plaintext,
554 plaintext_len, nonce, encryption_key) != 0) {
555 SET_ERRNO(ERROR_CRYPTO, "Encryption failed");
557 }
558
559 *ciphertext_len_out = required_size;
560 ctx->bytes_encrypted += plaintext_len;
561
562 // Increment rekey packet counter for rekeying trigger detection
563 ctx->rekey_packet_count++;
564
565 ASCII_OTEL_ATTR_INT("crypto.output.size", (int64_t)*ciphertext_len_out);
566 ascii_otel_metric(ASCII_OTEL_METRIC_CRYPTO_ENCRYPT_BYTES,
567 (double)plaintext_len);
568 return CRYPTO_OK;
569}
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define XSALSA20_NONCE_SIZE
XSalsa20 nonce size in bytes.
Definition sizes.h:44

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ascii_otel_metric(), ASCII_OTEL_SCOPE, crypto_context_t::bytes_encrypted, CRYPTO_ERROR_BUFFER_TOO_SMALL, CRYPTO_ERROR_ENCRYPTION, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE, CRYPTO_ERROR_NONCE_EXHAUSTED, crypto_is_ready(), CRYPTO_MAX_PLAINTEXT_SIZE, CRYPTO_OK, crypto_context_t::encryption_key_size, ERROR_BUFFER, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_password, crypto_context_t::initialized, crypto_context_t::key_exchange_complete, log_debug_every, crypto_context_t::mac_size, crypto_context_t::nonce_counter, crypto_context_t::nonce_size, crypto_context_t::password_key, crypto_context_t::rekey_packet_count, SAFE_MEMCPY, SET_ERRNO, crypto_context_t::shared_key, US_PER_SEC_INT, and XSALSA20_NONCE_SIZE.

Referenced by crypto_create_encrypted_packet(), and crypto_record_seal_into_domain().

◆ crypto_extract_auth_data()

void crypto_extract_auth_data ( const uint8_t * combined_data,
uint8_t * hmac_out,
uint8_t * challenge_out )

#include <include/ascii-chat/crypto/crypto.h>

Extract HMAC and challenge nonce from combined data.

Parameters
combined_dataCombined data received from peer (64 bytes)
hmac_outOutput buffer for HMAC (32 bytes)
challenge_outOutput buffer for challenge nonce (32 bytes)

Extracts HMAC and challenge nonce from combined buffer: [HMAC:32][nonce:32] Used to unpack authentication response data received from peer.

Note
Format: [HMAC:32][challenge_nonce:32] (64 bytes total)

Definition at line 1328 of file lib/crypto/crypto.c.

1329 {
1330 if (!combined_data || !hmac_out || !challenge_out) {
1331 SET_ERRNO(
1333 "Invalid parameters: combined_data=%p, hmac_out=%p, challenge_out=%p",
1334 combined_data, hmac_out, challenge_out);
1335 return;
1336 }
1337
1338 // Extract HMAC (first 32 bytes) and challenge nonce (last 32 bytes)
1339 memcpy(hmac_out, combined_data, HMAC_SHA256_SIZE);
1340 memcpy(challenge_out, combined_data + AUTH_CHALLENGE_SIZE,
1342}

References AUTH_CHALLENGE_SIZE, ERROR_INVALID_PARAM, HMAC_SHA256_SIZE, and SET_ERRNO.

◆ crypto_generate_keypair()

crypto_result_t crypto_generate_keypair ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Generate new X25519 key pair for key exchange.

Parameters
ctxCrypto context
Returns
CRYPTO_OK on success, error code on failure

Generates a new ephemeral X25519 key pair. Called automatically by crypto_init(). Can be called again to regenerate keys (e.g., for rekeying).

Definition at line 238 of file lib/crypto/crypto.c.

238 {
239 if (!ctx) {
240 SET_ERRNO(ERROR_INVALID_PARAM, "NULL context");
242 }
243
244 log_debug("About to call crypto_box_keypair");
245 // Generate X25519 key pair for key exchange
246 if (crypto_box_keypair(ctx->public_key, ctx->private_key) != 0) {
247 SET_ERRNO(ERROR_CRYPTO, "Failed to generate X25519 key pair");
249 }
250
251 log_debug("Generated X25519 key pair for key exchange");
252 return CRYPTO_OK;
253}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_GENERATION, CRYPTO_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, log_debug, crypto_context_t::private_key, crypto_context_t::public_key, and SET_ERRNO.

Referenced by crypto_init().

◆ crypto_generate_nonce()

crypto_result_t crypto_generate_nonce ( uint8_t nonce[32])

#include <include/ascii-chat/crypto/crypto.h>

Generate random nonce for authentication.

Parameters
nonceOutput buffer for 32-byte random nonce
Returns
CRYPTO_OK on success, error code on failure

Generates a cryptographically secure random nonce for authentication challenges. Uses libsodium's secure random number generator.

Note
Automatically initializes libsodium if not already initialized.

References AUTH_CHALLENGE_SIZE.

◆ crypto_get_public_key()

crypto_result_t crypto_get_public_key ( const crypto_context_t * ctx,
uint8_t * public_key_out )

#include <include/ascii-chat/crypto/crypto.h>

Get public key for sending to peer (step 1 of handshake).

Parameters
ctxCrypto context
public_key_outOutput buffer for public key (must be CRYPTO_PUBLIC_KEY_SIZE bytes)
Returns
CRYPTO_OK on success, error code on failure

Retrieves our ephemeral public key for transmission to the peer. This is the first step in the key exchange handshake.

Definition at line 259 of file lib/crypto/crypto.c.

260 {
261 if (!ctx || !ctx->initialized || !public_key_out) {
263 "Invalid parameters (ctx=%p, initialized=%d, public_key_out=%p)",
264 ctx, ctx ? ctx->initialized : 0, public_key_out);
266 }
267
268 // Bounds check to prevent buffer overflow
269 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE)
270 ? ctx->public_key_size
272 SAFE_MEMCPY(public_key_out, copy_size, ctx->public_key, copy_size);
273 return CRYPTO_OK;
274}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_INVALID_PARAM, crypto_context_t::initialized, crypto_context_t::public_key, crypto_context_t::public_key_size, SAFE_MEMCPY, SET_ERRNO, and X25519_KEY_SIZE.

◆ crypto_get_rekey_status()

void crypto_get_rekey_status ( const crypto_context_t * ctx,
char * status_buffer,
size_t buffer_size )

#include <include/ascii-chat/crypto/crypto.h>

Get the current rekeying state for debugging/logging.

Parameters
ctxCrypto context
status_bufferOutput buffer for status string
buffer_sizeSize of status buffer

Formats a human-readable status string with rekeying state:

  • Packet count since last rekey
  • Time since last rekey
  • Rekey in progress status
  • Failure count
  • Threshold values
Note
Safe to call with NULL ctx or buffer (does nothing).

Definition at line 1564 of file lib/crypto/crypto.c.

1565 {
1566 if (!ctx || !status_buffer || buffer_size == 0) {
1567 return;
1568 }
1569
1570 time_t now = time(NULL);
1571 time_t elapsed = now - ctx->rekey_last_time;
1572 time_t remaining_time = (ctx->rekey_time_threshold > elapsed)
1573 ? (ctx->rekey_time_threshold - elapsed)
1574 : 0;
1575 uint64_t remaining_packets =
1578 : 0;
1579
1580 safe_snprintf(status_buffer, buffer_size,
1581 "Rekey status: %s | "
1582 "Packets: %llu/%llu (%llu remaining) | "
1583 "Time: %ld/%ld sec (%ld sec remaining) | "
1584 "Rekeys: %llu | Failures: %d",
1585 ctx->rekey_in_progress ? "IN_PROGRESS" : "IDLE",
1586 (unsigned long long)ctx->rekey_packet_count,
1587 (unsigned long long)ctx->rekey_packet_threshold,
1588 (unsigned long long)remaining_packets, (long)elapsed,
1589 (long)ctx->rekey_time_threshold, (long)remaining_time,
1590 (unsigned long long)ctx->rekey_count, ctx->rekey_failure_count);
1591}
int buffer_size
Size of circular buffer.
Definition grep.c:69
unsigned long long uint64_t

References buffer_size, crypto_context_t::rekey_count, crypto_context_t::rekey_failure_count, crypto_context_t::rekey_in_progress, crypto_context_t::rekey_last_time, crypto_context_t::rekey_packet_count, crypto_context_t::rekey_packet_threshold, and crypto_context_t::rekey_time_threshold.

◆ crypto_get_status()

void crypto_get_status ( const crypto_context_t * ctx,
char * status_buffer,
size_t buffer_size )

#include <include/ascii-chat/crypto/crypto.h>

Get crypto context status information for debugging.

Parameters
ctxCrypto context
status_bufferOutput buffer for status string
buffer_sizeSize of status buffer

Formats a human-readable status string with context state information:

  • Initialization status
  • Password status
  • Key exchange status
  • Ready status
  • Encrypted/decrypted byte counts
  • Nonce counter value
Note
Safe to call with NULL ctx or buffer (does nothing).

Definition at line 688 of file lib/crypto/crypto.c.

689 {
690 if (!ctx || !status_buffer || buffer_size == 0) {
691 return;
692 }
693
694 if (!ctx->initialized) {
695 SAFE_SNPRINTF(status_buffer, buffer_size, "Not initialized");
696 return;
697 }
698
699 SAFE_SNPRINTF(status_buffer, buffer_size,
700 "Initialized: %s, Password: %s, Key Exchange: %s, Ready: %s, "
701 "Encrypted: %" PRIu64 " bytes, Decrypted: %" PRIu64
702 " bytes, Nonce: %" PRIu64,
703 ctx->initialized ? "yes" : "no",
704 ctx->has_password ? "yes" : "no",
705 ctx->key_exchange_complete ? "complete" : "incomplete",
706 crypto_is_ready(ctx) ? "yes" : "no", ctx->bytes_encrypted,
707 ctx->bytes_decrypted, ctx->nonce_counter);
708}
#define SAFE_SNPRINTF(buffer, buffer_size,...)

References buffer_size, crypto_context_t::bytes_decrypted, crypto_context_t::bytes_encrypted, crypto_is_ready(), crypto_context_t::has_password, crypto_context_t::initialized, crypto_context_t::key_exchange_complete, crypto_context_t::nonce_counter, and SAFE_SNPRINTF.

◆ crypto_init()

crypto_result_t crypto_init ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Initialize libsodium and crypto context.

Parameters
ctxCrypto context to initialize
Returns
CRYPTO_OK on success, error code on failure

Initializes libsodium (thread-safe, idempotent) and generates a new X25519 key pair for key exchange.

Note
libsodium initialization is global and thread-safe. Multiple calls to crypto_init() will only initialize libsodium once.
Generates a new ephemeral key pair automatically. The nonce counter starts at 1 (0 is reserved for testing).

Definition at line 92 of file lib/crypto/crypto.c.

92 {
93 if (!ctx) {
94 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p", ctx);
96 }
97
98 // Initialize libsodium
99 crypto_result_t result = init_libsodium();
100 if (result != CRYPTO_OK) {
101 return result;
102 }
103
104 // Clear context
105 secure_memzero(ctx, sizeof(crypto_context_t));
106
107 // Generate key pair for X25519 key exchange
108 result = crypto_generate_keypair(ctx);
109 if (result != CRYPTO_OK) {
110 return result;
111 }
112
113 ctx->initialized = true;
114 ctx->has_password = false;
115 ctx->key_exchange_complete = false;
116 ctx->peer_key_received = false;
117 ctx->handshake_complete = false;
118 ctx->encrypt_data = true; // Default: enable payload encryption
119 ctx->nonce_counter = 1; // Start from 1 (0 reserved for testing)
120 ctx->bytes_encrypted = 0;
121 ctx->bytes_decrypted = 0;
122
123 // Set default algorithm-specific parameters (can be overridden during
124 // handshake)
134 // signature_size and auth_public_key_size remain 0 until set by
135 // CRYPTO_PARAMETERS (must be 0 for unauthenticated format detection in
136 // crypto_handshake_client_key_exchange)
137
138 // Generate a random nonce prefix for this connection.
139 randombytes_buf(ctx->session_id, sizeof(ctx->session_id));
140
141 // Initialize rekeying state
142 ctx->rekey_packet_count = 0;
143 ctx->rekey_last_time = time(NULL); // Initialize to current time
144 ctx->rekey_last_request_time = 0; // No rekey request yet
145 ctx->rekey_in_progress = false;
146 ctx->rekey_failure_count = 0;
147 ctx->has_temp_key = false;
148 ctx->rekey_count = 0;
149
150 // SECURITY: Use production-safe rekey thresholds by default
151 // Rekey every 1 hour OR 1 million packets (whichever comes first)
152 // Only use test mode if explicitly requested via environment variable
153 if (is_test_environment()) {
156 char duration_str[TIME_DURATION_BUFFER_SIZE];
157 time_pretty(ctx->rekey_time_threshold, -1, duration_str,
158 sizeof(duration_str));
159 log_dev("Crypto context initialized with X25519 key exchange (TEST MODE "
160 "rekey thresholds: %llu packets, %s)",
161 (unsigned long long)ctx->rekey_packet_threshold, duration_str);
162 } else {
164 REKEY_DEFAULT_PACKET_THRESHOLD; // 1 million packets
166 REKEY_DEFAULT_TIME_THRESHOLD; // already in nanoseconds (3600 *
167 // NS_PER_SEC_INT)
168 char duration_str[TIME_DURATION_BUFFER_SIZE];
169 time_pretty(ctx->rekey_time_threshold, -1, duration_str,
170 sizeof(duration_str));
171 log_dev("Crypto context initialized with X25519 key exchange (rekey "
172 "thresholds: %llu packets, %s)",
173 (unsigned long long)ctx->rekey_packet_threshold, duration_str);
174 }
177}
#define REKEY_DEFAULT_TIME_THRESHOLD
Default rekey time threshold (1 hour in nanoseconds).
crypto_result_t crypto_generate_keypair(crypto_context_t *ctx)
Generate new X25519 key pair for key exchange.
#define REKEY_TEST_PACKET_THRESHOLD
Test mode rekey packet threshold (1000 packets).
#define REKEY_TEST_TIME_THRESHOLD
Test mode rekey time threshold (30 seconds in nanoseconds).
#define REKEY_DEFAULT_PACKET_THRESHOLD
Default rekey packet threshold (1 million packets).
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
asciichat_error_t crypto_session_create(crypto_context_t *crypto)
#define SECRETBOX_KEY_SIZE
Secretbox key size in bytes.
Definition sizes.h:54
#define ARGON2ID_SALT_SIZE
Argon2id salt size in bytes.
Definition sizes.h:52
#define POLY1305_MAC_SIZE
Poly1305 MAC size in bytes.
Definition sizes.h:46

References ARGON2ID_SALT_SIZE, ASCIICHAT_OK, AUTH_CHALLENGE_SIZE, crypto_context_t::auth_challenge_size, crypto_context_t::bytes_decrypted, crypto_context_t::bytes_encrypted, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_MEMORY, crypto_generate_keypair(), CRYPTO_OK, crypto_session_create(), crypto_context_t::encrypt_data, crypto_context_t::encryption_key_size, ERROR_INVALID_PARAM, crypto_context_t::handshake_complete, crypto_context_t::has_password, crypto_context_t::has_temp_key, HMAC_SHA256_SIZE, crypto_context_t::hmac_size, crypto_context_t::initialized, crypto_context_t::key_exchange_complete, log_dev, crypto_context_t::mac_size, crypto_context_t::nonce_counter, crypto_context_t::nonce_size, crypto_context_t::peer_key_received, POLY1305_MAC_SIZE, crypto_context_t::private_key_size, crypto_context_t::public_key_size, crypto_context_t::rekey_count, REKEY_DEFAULT_PACKET_THRESHOLD, REKEY_DEFAULT_TIME_THRESHOLD, crypto_context_t::rekey_failure_count, crypto_context_t::rekey_in_progress, crypto_context_t::rekey_last_request_time, crypto_context_t::rekey_last_time, crypto_context_t::rekey_packet_count, crypto_context_t::rekey_packet_threshold, REKEY_TEST_PACKET_THRESHOLD, REKEY_TEST_TIME_THRESHOLD, crypto_context_t::rekey_time_threshold, crypto_context_t::salt_size, SECRETBOX_KEY_SIZE, crypto_context_t::session_id, SET_ERRNO, crypto_context_t::shared_key_size, TIME_DURATION_BUFFER_SIZE, time_pretty(), X25519_KEY_SIZE, and XSALSA20_NONCE_SIZE.

Referenced by crypto_handshake_init(), and crypto_init_with_password().

◆ crypto_init_with_password()

crypto_result_t crypto_init_with_password ( crypto_context_t * ctx,
const char * password )

#include <include/ascii-chat/crypto/crypto.h>

Initialize with password-based encryption.

Parameters
ctxCrypto context to initialize
passwordPassword for key derivation
Returns
CRYPTO_OK on success, error code on failure

Initializes context and derives encryption key from password using Argon2id. The password is used as an additional layer on top of DH key exchange.

Note
Password must meet length requirements (8-256 characters).

Definition at line 179 of file lib/crypto/crypto.c.

180 {
181 if (!ctx || !password) {
182 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: ctx=%p, password=%p",
183 ctx, password);
185 }
186
187 if (strlen(password) == 0) {
188 SET_ERRNO(ERROR_INVALID_PARAM, "Password cannot be empty");
190 }
191
192 // First initialize basic crypto
193 crypto_result_t result = crypto_init(ctx);
194 if (result != CRYPTO_OK) {
195 return result;
196 }
197
198 // Derive password key
199 result = crypto_derive_password_key(ctx, password);
200 if (result != CRYPTO_OK) {
201 crypto_destroy(ctx);
202 return result;
203 }
204
205 ctx->has_password = true;
206
207 log_dev("Crypto context initialized with password-based encryption");
208 return CRYPTO_OK;
209}
crypto_result_t crypto_init(crypto_context_t *ctx)
Initialize libsodium and crypto context.
crypto_result_t crypto_derive_password_key(crypto_context_t *ctx, const char *password)
Derive key from password using Argon2id.
void crypto_destroy(crypto_context_t *ctx)
Cleanup crypto context with secure memory wiping.

References crypto_derive_password_key(), crypto_destroy(), CRYPTO_ERROR_INVALID_PARAMS, crypto_init(), CRYPTO_OK, ERROR_INVALID_PARAM, crypto_context_t::has_password, log_dev, and SET_ERRNO.

Referenced by crypto_handshake_init_with_password().

◆ crypto_is_ready()

bool crypto_is_ready ( const crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Check if key exchange is complete and ready for encryption.

Parameters
ctxCrypto context
Returns
true if key exchange is complete, false otherwise

Returns true only after both parties have exchanged public keys and the shared secret has been computed.

Definition at line 309 of file lib/crypto/crypto.c.

309 {
310 if (!ctx || !ctx->initialized) {
311 return false;
312 }
313
314 // Ready if either key exchange is complete OR password is set
315 return ctx->key_exchange_complete || ctx->has_password;
316}

References crypto_context_t::has_password, crypto_context_t::initialized, and crypto_context_t::key_exchange_complete.

Referenced by acip_packet_plan(), crypto_create_encrypted_packet(), crypto_decrypt(), crypto_encrypt(), crypto_get_status(), crypto_handshake_is_ready(), crypto_process_encrypted_packet(), packet_send_error(), packet_send_remote_log(), and send_packet_secure().

◆ crypto_process_auth_challenge()

crypto_result_t crypto_process_auth_challenge ( crypto_context_t * ctx,
const uint8_t * packet,
size_t packet_len )

#include <include/ascii-chat/crypto/crypto.h>

Process authentication challenge packet.

Parameters
ctxCrypto context (must be initialized)
packetChallenge packet received from peer
packet_lenLength of challenge packet
Returns
CRYPTO_OK on success, error code on failure

Processes an authentication challenge packet: [type:4][nonce:auth_challenge_size] Extracts the nonce and stores it in ctx->auth_nonce for generating the response.

Note
Packet format: [PACKET_TYPE_AUTH_CHALLENGE:4][nonce:32] Expected size: sizeof(uint32_t) + ctx->auth_challenge_size (typically 36 bytes)
The extracted nonce is stored in ctx->auth_nonce and should be used with crypto_compute_auth_response() to generate the authentication response.

Definition at line 1139 of file lib/crypto/crypto.c.

1141 {
1142 if (!ctx || !ctx->initialized || !packet) {
1144 "Invalid parameters (ctx=%p, initialized=%d, packet=%p)", ctx,
1145 ctx ? ctx->initialized : 0, packet);
1147 }
1148
1149 size_t expected_size =
1150 sizeof(uint32_t) + ctx->auth_challenge_size; // type + nonce
1151 if (packet_len != expected_size) {
1153 "Invalid packet size (expected=%zu, got=%zu)", expected_size,
1154 packet_len);
1156 }
1157
1158 // Unpack packet: [type:4][nonce:auth_challenge_size]
1159 uint32_t packet_type;
1160 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
1161
1162 if (packet_type != CRYPTO_PACKET_AUTH_CHALLENGE) {
1163 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)",
1164 CRYPTO_PACKET_AUTH_CHALLENGE, packet_type);
1166 }
1167
1168 // Store the nonce for HMAC computation (use buffer size for memcpy size,
1169 // actual size from context)
1170 SAFE_MEMCPY(ctx->auth_nonce, sizeof(ctx->auth_nonce),
1171 packet + sizeof(packet_type), ctx->auth_challenge_size);
1172
1173 log_debug("Auth challenge received and processed");
1174 return CRYPTO_OK;
1175}

References crypto_context_t::auth_challenge_size, crypto_context_t::auth_nonce, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_INVALID_PARAM, crypto_context_t::initialized, log_debug, SAFE_MEMCPY, and SET_ERRNO.

◆ crypto_process_auth_response()

crypto_result_t crypto_process_auth_response ( crypto_context_t * ctx,
const uint8_t * packet,
size_t packet_len )

#include <include/ascii-chat/crypto/crypto.h>

Process authentication response packet.

Parameters
ctxCrypto context (must be initialized and have completed key exchange)
packetResponse packet received from peer
packet_lenLength of response packet
Returns
CRYPTO_OK on success, error code on failure

Processes an authentication response packet containing HMAC. Verifies the HMAC using crypto_verify_auth_response().

Note
Packet format depends on authentication method:
  • Password: [HMAC:32][challenge_nonce:32] (64 bytes)
  • Signature: [signature:64][challenge_nonce:32] (96 bytes)
Warning
Context must have completed key exchange before calling this function.

Definition at line 1177 of file lib/crypto/crypto.c.

1179 {
1180 if (!ctx || !ctx->initialized || !packet) {
1182 "Invalid context or packet (ctx=%p, initialized=%d, packet=%p)",
1183 ctx, ctx ? ctx->initialized : 0, packet);
1185 }
1186
1187 size_t expected_size = sizeof(uint32_t) + 32; // type + hmac
1188 if (packet_len != expected_size) {
1190 "Invalid packet size (expected=%zu, got=%zu)", expected_size,
1191 packet_len);
1193 }
1194
1195 // Unpack packet: [type:4][hmac:32]
1196 uint32_t packet_type;
1197 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
1198
1199 if (packet_type != CRYPTO_PACKET_AUTH_RESPONSE) {
1201 "Invalid packet type (expected=0x%x, got=0x%x)",
1202 CRYPTO_PACKET_AUTH_RESPONSE, packet_type);
1204 }
1205
1206 const uint8_t *received_hmac = packet + sizeof(packet_type);
1207
1208 // Verify HMAC using shared secret
1209 if (!crypto_verify_hmac(ctx->shared_key, ctx->auth_nonce, received_hmac)) {
1210 SET_ERRNO(ERROR_CRYPTO, "HMAC verification failed");
1212 }
1213
1214 ctx->handshake_complete = true;
1215 log_debug("Authentication successful - handshake complete");
1216 return CRYPTO_OK;
1217}
bool crypto_verify_hmac(const uint8_t key[HMAC_SHA256_KEY_SIZE], const uint8_t data[AUTH_CHALLENGE_SIZE], const uint8_t expected_hmac[HMAC_SHA256_SIZE])

References crypto_context_t::auth_nonce, CRYPTO_ERROR_INVALID_MAC, CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, crypto_verify_hmac(), ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::handshake_complete, crypto_context_t::initialized, log_debug, SAFE_MEMCPY, SET_ERRNO, and crypto_context_t::shared_key.

◆ crypto_process_encrypted_packet()

crypto_result_t crypto_process_encrypted_packet ( crypto_context_t * ctx,
const uint8_t * packet,
size_t packet_len,
uint8_t * data_out,
size_t data_size,
size_t * data_len_out )

#include <include/ascii-chat/crypto/crypto.h>

Process received encrypted packet from peer.

Parameters
ctxCrypto context (must be initialized and ready)
packetEncrypted packet received from peer
packet_lenLength of packet
data_outOutput buffer for decrypted plaintext
data_sizeSize of output buffer
data_len_outOutput parameter for actual plaintext length
Returns
CRYPTO_OK on success, CRYPTO_ERROR_INVALID_MAC if MAC verification fails

Processes an encrypted data packet: [type:4][length:4][encrypted_data:var] Decrypts the data using crypto_decrypt().

Note
Packet format: [PACKET_TYPE_ENCRYPTED_DATA:4][data_length:4][encrypted_data] Encrypted data format: [nonce:24][encrypted_data][MAC:16] Plaintext size: data_length - nonce_size - mac_size
Context must be ready (crypto_is_ready() returns true) before calling.
Warning
Always check return value. CRYPTO_ERROR_INVALID_MAC indicates tampering or wrong key.

Definition at line 873 of file lib/crypto/crypto.c.

875 {
876 if (!ctx || !packet || !data_out || !data_len_out) {
877 SET_ERRNO(
879 "Invalid parameters (ctx=%p, packet=%p, data_out=%p, data_len_out=%p)",
880 ctx, packet, data_out, data_len_out);
882 }
883
884 if (!crypto_is_ready(ctx)) {
885 SET_ERRNO(ERROR_CRYPTO, "Crypto context not ready");
887 }
888
889 if (packet_len < sizeof(uint32_t) + sizeof(uint32_t)) {
890 SET_ERRNO(ERROR_INVALID_PARAM, "Packet too small (size=%zu)", packet_len);
892 }
893
894 // Unpack packet: [type:4][length:4][encrypted_data:var]
895 uint32_t packet_type;
896 uint32_t data_length;
897 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
898 SAFE_MEMCPY(&data_length, sizeof(data_length), packet + sizeof(packet_type),
899 sizeof(data_length));
900
901 if (packet_type != CRYPTO_PACKET_ENCRYPTED_DATA) {
902 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)",
903 CRYPTO_PACKET_ENCRYPTED_DATA, packet_type);
905 }
906
907 if (packet_len != sizeof(uint32_t) + sizeof(uint32_t) + data_length) {
909 "Packet length mismatch (expected=%zu, got=%zu)",
910 sizeof(uint32_t) + sizeof(uint32_t) + data_length, packet_len);
912 }
913
914 const uint8_t *encrypted_data = packet + sizeof(uint32_t) + sizeof(uint32_t);
915 return crypto_decrypt(ctx, encrypted_data, data_length, data_out, data_size,
916 data_len_out);
917}
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.

References crypto_decrypt(), CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_EXCHANGE_INCOMPLETE, crypto_is_ready(), ERROR_CRYPTO, ERROR_INVALID_PARAM, SAFE_MEMCPY, and SET_ERRNO.

◆ crypto_process_public_key_packet()

crypto_result_t crypto_process_public_key_packet ( crypto_context_t * ctx,
const uint8_t * packet,
size_t packet_len )

#include <include/ascii-chat/crypto/crypto.h>

Process received public key packet from peer.

Parameters
ctxCrypto context (must be initialized)
packetPublic key packet received from peer
packet_lenLength of packet
Returns
CRYPTO_OK on success, error code on failure

Processes a public key packet: [type:4][public_key:public_key_size] Extracts peer's public key and computes shared secret automatically.

Note
Packet format: [PACKET_TYPE_PUBLIC_KEY:4][peer_public_key:32] Expected size: sizeof(uint32_t) + ctx->public_key_size (typically 36 bytes)
Automatically computes shared secret via crypto_set_peer_public_key(). After this call, crypto_is_ready() may return true if key exchange is complete.

Definition at line 771 of file lib/crypto/crypto.c.

773 {
774 if (!ctx || !ctx->initialized || !packet) {
776 "Invalid parameters (ctx=%p, initialized=%d, packet=%p)", ctx,
777 ctx ? ctx->initialized : 0, packet);
779 }
780
781 size_t expected_size = sizeof(uint32_t) + ctx->public_key_size;
782 if (packet_len != expected_size) {
784 "Invalid packet size (expected=%zu, got=%zu)", expected_size,
785 packet_len);
787 }
788
789 // Unpack packet: [type:4][public_key:32]
790 uint32_t packet_type;
791 SAFE_MEMCPY(&packet_type, sizeof(packet_type), packet, sizeof(packet_type));
792
793 if (packet_type != CRYPTO_PACKET_PUBLIC_KEY) {
794 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid packet type (expected=%u, got=%u)",
795 CRYPTO_PACKET_PUBLIC_KEY, packet_type);
797 }
798
799 const uint8_t *peer_public_key = packet + sizeof(packet_type);
800 return crypto_set_peer_public_key(ctx, peer_public_key);
801}
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).

References CRYPTO_ERROR_INVALID_PARAMS, crypto_set_peer_public_key(), ERROR_INVALID_PARAM, crypto_context_t::initialized, crypto_context_t::public_key_size, SAFE_MEMCPY, and SET_ERRNO.

◆ crypto_random_bytes()

crypto_result_t crypto_random_bytes ( uint8_t * buffer,
size_t len )

#include <include/ascii-chat/crypto/crypto.h>

Generate cryptographically secure random bytes.

Parameters
bufferOutput buffer for random bytes
lenNumber of random bytes to generate (must be > 0)
Returns
CRYPTO_OK on success, error code on failure

Uses libsodium's secure random number generator (randombytes_buf). Suitable for generating nonces, keys, salts, and other cryptographic material.

Note
Automatically initializes libsodium if not already initialized.
Warning
Returns CRYPTO_ERROR_INVALID_PARAMS if buffer is NULL or len is 0.

Definition at line 717 of file lib/crypto/crypto.c.

717 {
718 if (!buffer || len == 0) {
719 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters (buffer=%p, len=%zu)",
720 buffer, len);
722 }
723
724 crypto_result_t result = init_libsodium();
725 if (result != CRYPTO_OK) {
726 return result;
727 }
728
729 randombytes_buf(buffer, len);
730 return CRYPTO_OK;
731}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ crypto_rekey_abort()

void crypto_rekey_abort ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Abort rekeying and fallback to old keys.

Parameters
ctxCrypto context

Aborts ongoing rekey and clears temp_* keys. Called on rekey failure (timeout, bad keys, decryption failure, etc.).

Note
Clears temp_* keys and sets rekey_in_progress = false.
Old keys remain active (no service interruption).
Increments rekey_failure_count for exponential backoff.

Definition at line 1541 of file lib/crypto/crypto.c.

1541 {
1542 if (!ctx) {
1543 return;
1544 }
1545
1546 log_warn("Aborting rekey (attempt %d failed), keeping old encryption key",
1547 ctx->rekey_failure_count + 1);
1548
1549 // Wipe temporary keys securely
1550 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1551 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1552 secure_memzero(ctx->temp_shared_key, sizeof(ctx->temp_shared_key));
1553
1554 // Reset rekey state
1555 ctx->has_temp_key = false;
1556 ctx->rekey_in_progress = false;
1557
1558 // Increment failure counter for exponential backoff
1559 ctx->rekey_failure_count++;
1560
1561 // Continue using old key - no disruption to connection
1562}

References crypto_context_t::has_temp_key, log_warn, crypto_context_t::rekey_failure_count, crypto_context_t::rekey_in_progress, crypto_context_t::temp_private_key, crypto_context_t::temp_public_key, and crypto_context_t::temp_shared_key.

Referenced by crypto_rekey_process_response(), and crypto_rekey_session_cleanup().

◆ crypto_rekey_commit()

crypto_result_t crypto_rekey_commit ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Commit to new keys after successful REKEY_COMPLETE.

Parameters
ctxCrypto context
Returns
CRYPTO_OK on success, error code on failure

Switches from old shared_key to temp_shared_key, resets counters. Called after REKEY_COMPLETE is verified (decrypts successfully with new key).

Note
Replaces shared_key with temp_shared_key.
Resets rekey_packet_count, rekey_last_time, and rekey_in_progress.
Clears temp_* keys (they are now the active keys).
Warning
Only call after verifying REKEY_COMPLETE decrypts with new key.

Definition at line 1495 of file lib/crypto/crypto.c.

1495 {
1496 if (!ctx || !ctx->initialized) {
1497 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid context");
1499 }
1500
1501 if (!ctx->rekey_in_progress || !ctx->has_temp_key) {
1502 SET_ERRNO(ERROR_CRYPTO, "No rekey in progress to commit");
1504 }
1505
1506 // Wipe old shared secret securely
1507 secure_memzero(ctx->shared_key, sizeof(ctx->shared_key));
1508
1509 // Switch to new shared secret
1510 SAFE_MEMCPY(ctx->shared_key, sizeof(ctx->shared_key), ctx->temp_shared_key,
1511 sizeof(ctx->temp_shared_key));
1512
1513 // Reset nonce counter to 1 (fresh start with new key)
1514 ctx->nonce_counter = 1;
1515
1516 // Generate a new random nonce prefix for this key epoch.
1517 randombytes_buf(ctx->session_id, sizeof(ctx->session_id));
1518
1519 // Reset rekey tracking
1520 ctx->rekey_packet_count = 0;
1521 ctx->rekey_last_time = time(NULL);
1522 ctx->rekey_count++;
1523
1524 // Clear rekey state
1525 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1526 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1527 secure_memzero(ctx->temp_shared_key, sizeof(ctx->temp_shared_key));
1528 ctx->has_temp_key = false;
1529 ctx->rekey_in_progress = false;
1530
1531 // Reset failure counter on successful rekey
1532 ctx->rekey_failure_count = 0;
1533
1534 log_debug("Rekey committed successfully (rekey #%llu, nonce reset to 1, new "
1535 "session_id generated)",
1536 (unsigned long long)ctx->rekey_count);
1537
1538 return CRYPTO_OK;
1539}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_REKEY_FAILED, CRYPTO_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_temp_key, crypto_context_t::initialized, log_debug, crypto_context_t::nonce_counter, crypto_context_t::rekey_count, crypto_context_t::rekey_failure_count, crypto_context_t::rekey_in_progress, crypto_context_t::rekey_last_time, crypto_context_t::rekey_packet_count, SAFE_MEMCPY, crypto_context_t::session_id, SET_ERRNO, crypto_context_t::shared_key, crypto_context_t::temp_private_key, crypto_context_t::temp_public_key, and crypto_context_t::temp_shared_key.

Referenced by crypto_record_commit_epoch().

◆ crypto_rekey_init()

crypto_result_t crypto_rekey_init ( crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Initiate rekeying by generating new ephemeral keys.

Parameters
ctxCrypto context
Returns
CRYPTO_OK on success, error code on failure

Generates new ephemeral key pair and stores in temp_* fields. Called by the initiator (client or server) before sending REKEY_REQUEST.

Note
New keys are stored in temp_public_key and temp_private_key. They are NOT active until crypto_rekey_commit() is called.
Sets ctx->rekey_in_progress = true and updates rekey_last_request_time.
Warning
Do not call if rekey is already in progress.

Definition at line 1383 of file lib/crypto/crypto.c.

1383 {
1384 if (!ctx || !ctx->initialized) {
1385 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid context");
1387 }
1388
1389 if (ctx->rekey_in_progress) {
1390 SET_ERRNO(ERROR_CRYPTO, "Rekey already in progress");
1392 }
1393
1394 // Rate limiting: check minimum interval since last rekey
1395 time_t now = time(NULL);
1396 time_t since_last_rekey = now - ctx->rekey_last_time;
1397 time_t min_interval_seconds = (time_t)(REKEY_MIN_INTERVAL / NS_PER_SEC_INT);
1398 if (since_last_rekey < min_interval_seconds) {
1399 char elapsed_str[TIME_DURATION_BUFFER_SIZE],
1401 time_pretty((uint64_t)(since_last_rekey * 1e9), -1, elapsed_str,
1402 sizeof(elapsed_str));
1403 time_pretty((uint64_t)(min_interval_seconds * 1e9), -1, min_str,
1404 sizeof(min_str));
1405 log_warn("Rekey rate limited: %s since last rekey (minimum: %s)",
1406 elapsed_str, min_str);
1408 }
1409
1410 // Check if too many consecutive failures
1412 log_error("Too many consecutive rekey failures (%d), giving up",
1413 ctx->rekey_failure_count);
1415 }
1416
1417 // Generate new ephemeral X25519 keypair for rekeying
1418 if (crypto_box_keypair(ctx->temp_public_key, ctx->temp_private_key) != 0) {
1419 SET_ERRNO(ERROR_CRYPTO, "Failed to generate rekey ephemeral keypair");
1421 }
1422
1423 ctx->rekey_in_progress = true;
1424 ctx->has_temp_key = true;
1425
1426 log_debug(
1427 "Rekey initiated (packets: %llu, time elapsed: %ld sec, attempt %d)",
1428 (unsigned long long)ctx->rekey_packet_count, (long)since_last_rekey,
1429 ctx->rekey_failure_count + 1);
1430
1431 return CRYPTO_OK;
1432}
#define REKEY_MIN_INTERVAL
Minimum time interval between rekey requests (3 seconds in nanoseconds for testing,...
#define REKEY_MAX_FAILURE_COUNT
Maximum consecutive rekey failures before giving up.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define NS_PER_SEC_INT
Definition time.h:173

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_GENERATION, CRYPTO_ERROR_REKEY_FAILED, CRYPTO_ERROR_REKEY_IN_PROGRESS, CRYPTO_ERROR_REKEY_RATE_LIMITED, CRYPTO_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_temp_key, crypto_context_t::initialized, log_debug, log_error, log_warn, NS_PER_SEC_INT, crypto_context_t::rekey_failure_count, crypto_context_t::rekey_in_progress, crypto_context_t::rekey_last_time, REKEY_MAX_FAILURE_COUNT, REKEY_MIN_INTERVAL, crypto_context_t::rekey_packet_count, SET_ERRNO, crypto_context_t::temp_private_key, crypto_context_t::temp_public_key, TIME_DURATION_BUFFER_SIZE, and time_pretty().

Referenced by crypto_rekey_session_tick().

◆ crypto_rekey_process_request()

crypto_result_t crypto_rekey_process_request ( crypto_context_t * ctx,
const uint8_t * peer_new_public_key )

#include <include/ascii-chat/crypto/crypto.h>

Process REKEY_REQUEST from peer (responder side).

Parameters
ctxCrypto context
peer_new_public_keyPeer's new ephemeral public key (32 bytes)
Returns
CRYPTO_OK on success, error code on failure

Processes peer's new ephemeral public key from REKEY_REQUEST. Generates our own new ephemeral keys and computes new shared secret.

Note
Generates new temp_* keys and computes temp_shared_key. Keys are NOT active until crypto_rekey_commit() is called.
Should send REKEY_RESPONSE with our new public key after this call.

Definition at line 1435 of file lib/crypto/crypto.c.

1436 {
1437 if (!ctx || !ctx->initialized || !peer_new_public_key) {
1438 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
1440 }
1441
1442 // Generate our own new ephemeral keypair (responder side)
1443 if (crypto_box_keypair(ctx->temp_public_key, ctx->temp_private_key) != 0) {
1444 SET_ERRNO(ERROR_CRYPTO, "Failed to generate rekey ephemeral keypair");
1446 }
1447
1448 // Compute new shared secret: DH(our_new_private_key, peer_new_public_key)
1449 if (crypto_scalarmult(ctx->temp_shared_key, ctx->temp_private_key,
1450 peer_new_public_key) != 0) {
1451 SET_ERRNO(ERROR_CRYPTO, "Failed to compute rekey shared secret");
1452 secure_memzero(ctx->temp_private_key, sizeof(ctx->temp_private_key));
1453 secure_memzero(ctx->temp_public_key, sizeof(ctx->temp_public_key));
1455 }
1456
1457 ctx->rekey_in_progress = true;
1458 ctx->has_temp_key = true;
1459
1460 log_debug(
1461 "Rekey request processed (responder side), new shared secret computed");
1462
1463 return CRYPTO_OK;
1464}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_GENERATION, CRYPTO_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_temp_key, crypto_context_t::initialized, log_debug, crypto_context_t::rekey_in_progress, SET_ERRNO, crypto_context_t::temp_private_key, crypto_context_t::temp_public_key, and crypto_context_t::temp_shared_key.

Referenced by crypto_rekey_session_tick().

◆ crypto_rekey_process_response()

crypto_result_t crypto_rekey_process_response ( crypto_context_t * ctx,
const uint8_t * peer_new_public_key )

#include <include/ascii-chat/crypto/crypto.h>

Process REKEY_RESPONSE from peer (initiator side).

Parameters
ctxCrypto context
peer_new_public_keyPeer's new ephemeral public key (32 bytes)
Returns
CRYPTO_OK on success, error code on failure

Processes peer's new ephemeral public key from REKEY_RESPONSE. Computes new shared secret using our temp_private_key and peer's temp_public_key.

Note
Computes temp_shared_key. Keys are NOT active until crypto_rekey_commit() is called.
Should send REKEY_COMPLETE encrypted with NEW key after this call.

Definition at line 1467 of file lib/crypto/crypto.c.

1468 {
1469 if (!ctx || !ctx->initialized || !peer_new_public_key) {
1470 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
1472 }
1473
1474 if (!ctx->rekey_in_progress || !ctx->has_temp_key) {
1475 SET_ERRNO(ERROR_CRYPTO, "No rekey in progress");
1477 }
1478
1479 // Compute new shared secret: DH(our_new_private_key, peer_new_public_key)
1480 // Use crypto_scalarmult to produce raw 32-byte shared secret for
1481 // crypto_secretbox
1482 if (crypto_scalarmult(ctx->temp_shared_key, ctx->temp_private_key,
1483 peer_new_public_key) != 0) {
1484 SET_ERRNO(ERROR_CRYPTO, "Failed to compute rekey shared secret");
1485 crypto_rekey_abort(ctx);
1487 }
1488
1489 log_debug(
1490 "Rekey response processed (initiator side), new shared secret computed");
1491
1492 return CRYPTO_OK;
1493}
void crypto_rekey_abort(crypto_context_t *ctx)
Abort rekeying and fallback to old keys.

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_GENERATION, CRYPTO_ERROR_REKEY_FAILED, CRYPTO_OK, crypto_rekey_abort(), ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::has_temp_key, crypto_context_t::initialized, log_debug, crypto_context_t::rekey_in_progress, SET_ERRNO, crypto_context_t::temp_private_key, and crypto_context_t::temp_shared_key.

Referenced by crypto_rekey_session_receive().

◆ crypto_result_to_string()

const char * crypto_result_to_string ( crypto_result_t result)

#include <include/ascii-chat/crypto/crypto.h>

Convert crypto result to human-readable string.

Parameters
resultCrypto result code
Returns
Human-readable error string (never NULL)

Returns a descriptive string for each crypto_result_t value. Useful for logging and error reporting.

Definition at line 680 of file lib/crypto/crypto.c.

680 {
681 int idx = -result; // CRYPTO_OK=0, errors are negative
682 if (idx >= 0 && (size_t)idx < CRYPTO_RESULT_STRING_COUNT) {
683 return g_crypto_result_strings[idx];
684 }
685 return "Unknown error";
686}
#define CRYPTO_RESULT_STRING_COUNT

References CRYPTO_RESULT_STRING_COUNT.

Referenced by crypto_handshake_client_auth_response(), crypto_handshake_client_key_exchange(), crypto_handshake_init(), crypto_handshake_init_with_password(), crypto_handshake_server_auth_challenge(), and crypto_handshake_server_complete().

◆ crypto_secure_compare()

bool crypto_secure_compare ( const uint8_t * lhs,
const uint8_t * rhs,
size_t len )

#include <include/ascii-chat/crypto/crypto.h>

Secure constant-time comparison of byte arrays.

Parameters
lhsFirst byte array
rhsSecond byte array
lenLength of arrays to compare
Returns
true if arrays are equal, false otherwise

Uses constant-time comparison (sodium_memcmp) to prevent timing attacks. Always compares all bytes, regardless of where difference is found.

Note
Use this for comparing sensitive data: keys, MACs, HMACs, signatures. Do NOT use regular memcmp() for cryptographic comparisons.
Warning
Returns false if either pointer is NULL.

Definition at line 710 of file lib/crypto/crypto.c.

710 {
711 if (!lhs || !rhs) {
712 return false;
713 }
714 return sodium_memcmp(lhs, rhs, len) == 0;
715}

◆ crypto_set_peer_public_key()

crypto_result_t crypto_set_peer_public_key ( crypto_context_t * ctx,
const uint8_t * peer_public_key )

#include <include/ascii-chat/crypto/crypto.h>

Set peer's public key and compute shared secret (step 2 of handshake).

Parameters
ctxCrypto context
peer_public_keyPeer's ephemeral public key (CRYPTO_PUBLIC_KEY_SIZE bytes)
Returns
CRYPTO_OK on success, error code on failure

Receives peer's public key and computes the shared secret using X25519. After this call, crypto_is_ready() will return true.

Note
This function computes the shared secret immediately. The shared secret is used for encryption/decryption after key exchange is complete.

Definition at line 276 of file lib/crypto/crypto.c.

277 {
278 if (!ctx || !ctx->initialized || !peer_public_key) {
280 "Invalid parameters (ctx=%p, initialized=%d, peer_public_key=%p)",
281 ctx, ctx ? ctx->initialized : 0, peer_public_key);
283 }
284
285 // Store peer's public key
286 // Bounds check to prevent buffer overflow
287 size_t copy_size = (ctx->public_key_size <= X25519_KEY_SIZE)
288 ? ctx->public_key_size
290 SAFE_MEMCPY(ctx->peer_public_key, copy_size, peer_public_key, copy_size);
291 ctx->peer_key_received = true;
292
293 // Compute shared secret using X25519 and crypto_scalarmult (compatible with
294 // secretbox) This produces a raw 32-byte shared secret suitable for
295 // crypto_secretbox
296 if (crypto_scalarmult(ctx->shared_key, ctx->private_key, peer_public_key) !=
297 0) {
299 "Failed to compute shared secret from peer public key");
301 }
302
303 ctx->key_exchange_complete = true;
304
305 log_debug("Key exchange complete");
306 return CRYPTO_OK;
307}

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_ERROR_KEY_GENERATION, CRYPTO_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, crypto_context_t::initialized, crypto_context_t::key_exchange_complete, log_debug, crypto_context_t::peer_key_received, crypto_context_t::peer_public_key, crypto_context_t::private_key, crypto_context_t::public_key_size, SAFE_MEMCPY, SET_ERRNO, crypto_context_t::shared_key, and X25519_KEY_SIZE.

Referenced by crypto_handshake_client_key_exchange(), crypto_handshake_server_auth_challenge(), and crypto_process_public_key_packet().

◆ crypto_should_rekey()

bool crypto_should_rekey ( const crypto_context_t * ctx)

#include <include/ascii-chat/crypto/crypto.h>

Check if rekeying should be triggered based on time or packet count thresholds.

Parameters
ctxCrypto context
Returns
true if rekey should be initiated, false otherwise

Checks if rekeying should be triggered based on:

  • Time since last rekey >= rekey_time_threshold
  • Packet count since last rekey >= rekey_packet_threshold
  • Minimum interval since last rekey request (DDoS protection)
Note
Should be called after each packet encryption.
Test environment: Automatically uses test thresholds if TESTING is set.
DDoS protection: Requires at least REKEY_MIN_REQUEST_INTERVAL seconds between requests.

Definition at line 1348 of file lib/crypto/crypto.c.

1348 {
1349 if (!ctx || !ctx->initialized) {
1350 return false;
1351 }
1352
1353 // Don't trigger rekey if one is already in progress
1354 if (ctx->rekey_in_progress) {
1355 return false;
1356 }
1357
1358 // Don't trigger rekey if handshake isn't complete yet
1359 if (!ctx->handshake_complete) {
1360 return false;
1361 }
1362
1363 // Check packet count threshold
1364 if (ctx->rekey_packet_count >= ctx->rekey_packet_threshold) {
1365 log_debug("Rekey triggered: packet count (%llu) >= threshold (%llu)",
1366 (unsigned long long)ctx->rekey_packet_count,
1367 (unsigned long long)ctx->rekey_packet_threshold);
1368 return true;
1369 }
1370
1371 // Check time threshold
1372 time_t now = time(NULL);
1373 time_t elapsed = now - ctx->rekey_last_time;
1374 if (elapsed >= ctx->rekey_time_threshold) {
1375 log_debug("Rekey triggered: time elapsed (%ld sec) >= threshold (%ld sec)",
1376 (long)elapsed, (long)ctx->rekey_time_threshold);
1377 return true;
1378 }
1379
1380 return false;
1381}

References crypto_context_t::handshake_complete, crypto_context_t::initialized, log_debug, crypto_context_t::rekey_in_progress, crypto_context_t::rekey_last_time, crypto_context_t::rekey_packet_count, crypto_context_t::rekey_packet_threshold, and crypto_context_t::rekey_time_threshold.

◆ crypto_sign_ephemeral_key()

asciichat_error_t crypto_sign_ephemeral_key ( const private_key_t * private_key,
const uint8_t * ephemeral_key,
size_t ephemeral_key_size,
uint8_t * signature_out )

#include <include/ascii-chat/crypto/crypto.h>

Sign ephemeral key with private key.

Parameters
private_keyEd25519 private key for signing (64 bytes)
ephemeral_keyEphemeral public key to sign (variable size)
ephemeral_key_sizeSize of ephemeral key (typically 32 bytes for X25519)
signature_outOutput buffer for Ed25519 signature (64 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Signs ephemeral public key with Ed25519 identity key. Used during authenticated key exchange to prove server identity.

Note
Signature is over the ephemeral public key itself. Allows verification without revealing the identity key.
Used in authenticated key exchange format (ephemeral + identity + signature).

Definition at line 1281 of file lib/crypto/crypto.c.

1284 {
1285 if (!private_key || !ephemeral_key || !signature_out) {
1287 "Invalid parameters: private_key=%p, ephemeral_key=%p, "
1288 "signature_out=%p",
1289 private_key, ephemeral_key, signature_out);
1290 }
1291
1292 if (ephemeral_key_size == 0) {
1293 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ephemeral key size: %zu",
1294 ephemeral_key_size);
1295 return ERROR_INVALID_PARAM;
1296 }
1297
1298 // Sign the ephemeral key with our Ed25519 private key
1299 if (private_key->type == KEY_TYPE_ED25519) {
1300 if (crypto_sign_detached(signature_out, NULL, ephemeral_key,
1301 ephemeral_key_size,
1302 private_key->key.ed25519) != 0) {
1303 return SET_ERRNO(ERROR_CRYPTO, "Failed to sign ephemeral key");
1304 }
1305 } else {
1306 return SET_ERRNO(ERROR_CRYPTO, "Unsupported private key type for signing");
1307 }
1308
1309 return ASCIICHAT_OK;
1310}
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:116
key_type_t type
Definition key_types.h:114
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_ED25519
Definition key_types.h:61

References ASCIICHAT_OK, private_key_t::ed25519, ERROR_CRYPTO, ERROR_INVALID_PARAM, private_key_t::key, KEY_TYPE_ED25519, SET_ERRNO, and private_key_t::type.

◆ crypto_validate_password()

crypto_result_t crypto_validate_password ( const char * password)

#include <include/ascii-chat/crypto/crypto.h>

Validate password length requirements.

Parameters
passwordPassword to validate
Returns
CRYPTO_OK if valid, CRYPTO_ERROR_INVALID_PARAMS if too short/long

Validates that password meets length requirements (MIN_PASSWORD_LENGTH to MAX_PASSWORD_LENGTH characters).

Note
Password must be between MIN_PASSWORD_LENGTH (8) and MAX_PASSWORD_LENGTH (256) characters.

Definition at line 322 of file lib/crypto/crypto.c.

322 {
323 if (!password) {
324 SET_ERRNO(ERROR_INVALID_PARAM, "Password is NULL");
326 }
327
328 size_t password_len = strlen(password);
329
330 if (password_len < MIN_PASSWORD_LENGTH) {
332 "Password too short (minimum %d characters, got %zu)",
333 MIN_PASSWORD_LENGTH, password_len);
335 }
336
337 if (password_len > MAX_PASSWORD_LENGTH) {
339 "Password too long (maximum %d characters, got %zu)",
340 MAX_PASSWORD_LENGTH, password_len);
342 }
343
344 return CRYPTO_OK;
345}
#define MIN_PASSWORD_LENGTH
Minimum password length (8 characters).
Definition sizes.h:24
#define MAX_PASSWORD_LENGTH
Maximum password length (256 characters).
Definition sizes.h:26

References CRYPTO_ERROR_INVALID_PARAMS, CRYPTO_OK, ERROR_INVALID_PARAM, MAX_PASSWORD_LENGTH, MIN_PASSWORD_LENGTH, and SET_ERRNO.

Referenced by crypto_derive_password_encryption_key(), and crypto_derive_password_key().

◆ crypto_verify_auth_response()

bool crypto_verify_auth_response ( const crypto_context_t * ctx,
const uint8_t nonce[32],
const uint8_t expected_hmac[32] )

#include <include/ascii-chat/crypto/crypto.h>

Verify authentication response HMAC bound to DH shared_secret.

Parameters
ctxCrypto context with keys (must have completed key exchange)
nonceChallenge nonce that was sent (32 bytes)
expected_hmacExpected HMAC to verify (32 bytes)
Returns
true if HMAC is valid, false otherwise

Verifies: HMAC(auth_key, nonce || shared_secret)

Note
Key selection: Uses password_key if available, otherwise uses shared_key. Must match the key used by crypto_compute_auth_response() on the peer side.
Key exchange requirement: ctx->key_exchange_complete must be true. Returns false if key exchange is not complete.
Warning
Always check return value. False indicates authentication failure or wrong key.

References AUTH_CHALLENGE_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_verify_hmac()

bool crypto_verify_hmac ( const uint8_t key[32],
const uint8_t data[32],
const uint8_t expected_hmac[32] )

#include <include/ascii-chat/crypto/crypto.h>

Verify HMAC-SHA256 for fixed 32-byte data.

Parameters
keyHMAC key (32 bytes)
dataData that was authenticated (32 bytes)
expected_hmacExpected HMAC to verify (32 bytes)
Returns
true if HMAC is valid, false otherwise

Verifies HMAC-SHA256 using constant-time comparison. Prevents timing attacks during verification.

Note
Returns false if any parameter is NULL.

References AUTH_CHALLENGE_SIZE, HMAC_SHA256_KEY_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_verify_hmac_ex()

bool crypto_verify_hmac_ex ( const uint8_t key[32],
const uint8_t * data,
size_t data_len,
const uint8_t expected_hmac[32] )

#include <include/ascii-chat/crypto/crypto.h>

Verify HMAC-SHA256 for variable-length data.

Parameters
keyHMAC key (32 bytes)
dataData that was authenticated (variable length)
data_lenLength of data (must be > 0)
expected_hmacExpected HMAC to verify (32 bytes)
Returns
true if HMAC is valid, false otherwise

Verifies HMAC-SHA256 using constant-time comparison. Prevents timing attacks during verification.

Note
Returns false if any parameter is NULL or data_len is 0.

References HMAC_SHA256_KEY_SIZE, and HMAC_SHA256_SIZE.

◆ crypto_verify_password()

bool crypto_verify_password ( const crypto_context_t * ctx,
const char * password )

#include <include/ascii-chat/crypto/crypto.h>

Verify password matches stored salt/key.

Parameters
ctxCrypto context (must be initialized and have password)
passwordPassword to verify
Returns
true if password matches, false otherwise

Verifies that the provided password, when derived with the stored salt, produces the same key as stored in the context.

Note
Uses constant-time comparison to prevent timing attacks.
Salt: Uses same deterministic salt as crypto_derive_password_key().

Definition at line 391 of file lib/crypto/crypto.c.

391 {
392 if (!ctx || !ctx->initialized || !ctx->has_password || !password) {
393 return false;
394 }
395
396 uint8_t test_key[SECRETBOX_KEY_SIZE]; // Use maximum size for buffer
397
398 // Use the same deterministic salt for verification
399 // Salt must be exactly ARGON2ID_SALT_SIZE (32) bytes
400 const char *deterministic_salt = "ascii-chat-password-salt-v1";
401 uint8_t salt[ARGON2ID_SALT_SIZE]; // Use maximum size for buffer
402 size_t salt_str_len = strlen(deterministic_salt);
403
404 // Zero-initialize the salt buffer first
405 memset(salt, 0, ARGON2ID_SALT_SIZE);
406
407 // Copy the salt string (will be padded with zeros to ctx->salt_size)
408 memcpy(salt, deterministic_salt,
409 (salt_str_len < ctx->salt_size) ? salt_str_len : ctx->salt_size);
410
411 // Derive key with same salt
412 if (crypto_pwhash(test_key, ctx->encryption_key_size, password,
413 strlen(password), salt, crypto_pwhash_OPSLIMIT_INTERACTIVE,
414 crypto_pwhash_MEMLIMIT_INTERACTIVE,
415 crypto_pwhash_ALG_DEFAULT) != 0) {
416 secure_memzero(test_key, sizeof(test_key));
417 return false;
418 }
419
420 // Constant-time comparison
421 bool match = (sodium_memcmp(test_key, ctx->password_key,
422 ctx->encryption_key_size) == 0);
423
424 secure_memzero(test_key, sizeof(test_key));
425 return match;
426}

References ARGON2ID_SALT_SIZE, crypto_context_t::encryption_key_size, crypto_context_t::has_password, crypto_context_t::initialized, crypto_context_t::password_key, crypto_context_t::salt_size, and SECRETBOX_KEY_SIZE.

◆ crypto_verify_peer_signature()

asciichat_error_t crypto_verify_peer_signature ( const uint8_t * peer_public_key,
const uint8_t * ephemeral_key,
size_t ephemeral_key_size,
const uint8_t * signature )

#include <include/ascii-chat/crypto/crypto.h>

Verify peer's signature on ephemeral key.

Parameters
peer_public_keyPeer's Ed25519 public key (32 bytes)
ephemeral_keyEphemeral public key that was signed (variable size)
ephemeral_key_sizeSize of ephemeral key (typically 32 bytes for X25519)
signatureEd25519 signature (64 bytes)
Returns
ASCIICHAT_OK if signature is valid, error code on failure

Verifies Ed25519 signature on ephemeral public key using peer's identity key. Used during authenticated key exchange to verify server identity.

Note
Signature is over the ephemeral public key itself, proving ownership of the identity key without revealing it.
Used in authenticated key exchange format (ephemeral + identity + signature).

Definition at line 1256 of file lib/crypto/crypto.c.

1259 {
1260 if (!peer_public_key || !ephemeral_key || !signature) {
1262 "Invalid parameters: peer_public_key=%p, "
1263 "ephemeral_key=%p, signature=%p",
1264 peer_public_key, ephemeral_key, signature);
1265 }
1266
1267 if (ephemeral_key_size == 0) {
1268 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ephemeral key size: %zu",
1269 ephemeral_key_size);
1270 }
1271
1272 // Verify the signature using Ed25519
1273 if (crypto_sign_verify_detached(signature, ephemeral_key, ephemeral_key_size,
1274 peer_public_key) != 0) {
1275 return SET_ERRNO(ERROR_CRYPTO, "Peer signature verification failed");
1276 }
1277
1278 return ASCIICHAT_OK;
1279}

References ASCIICHAT_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ display_mitm_warning()

bool display_mitm_warning ( const char * server_ip,
uint16_t port,
const uint8_t expected_key[32],
const uint8_t received_key[32] )

#include <include/ascii-chat/crypto/known_hosts.h>

Display MITM warning with key comparison and prompt user for confirmation.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
expected_keyFirst stored server key (32 bytes), or NULL if no stored public identity is available
received_keyReceived server key from connection (32 bytes, must not be NULL)
Returns
true if user accepts the risk and wants to continue, false otherwise

Displays man-in-the-middle warning with key comparison and prompts user for confirmation. Shows both expected and received keys in hex format for comparison.

Note
Warning display: Shows formatted warning message with:
  • Server IP:port
  • Expected key fingerprint (SHA256)
  • Received key fingerprint (SHA256)
  • Prompt for user confirmation
Key fingerprints: Displays SHA256 fingerprints of both keys for easy comparison. Fingerprints are displayed in hex format (64 hex chars).
User prompt: Prompts user to accept risk (continue) or abort connection. Returns true if user accepts, false if user aborts.
Non-interactive mode: If not connected to TTY (snapshot mode), automatically accepts the connection (returns true). This allows automated connections.
Security: Key mismatch indicates potential MITM attack or key rotation. User should verify keys before accepting.
Warning
Always check return value. If false, connection should be aborted.
MITM risk: Key mismatch may indicate man-in-the-middle attack. User should verify keys before accepting connection.

References ED25519_PUBLIC_KEY_SIZE.

◆ free_ta_contents()

void free_ta_contents ( br_x509_trust_anchor * ta)

#include <include/ascii-chat/crypto/pem.h>

Free the contents of a trust anchor.

Parameters
taPointer to trust anchor to free (must not be NULL)

Releases all dynamically allocated memory within a trust anchor structure, but does not free the structure itself. Call this for each trust anchor before freeing the anchor_list buffer.

Note
Memory cleanup: Frees certificate data, public key, and other dynamically allocated fields within trust anchor structure.
Structure preservation: Does not free the trust anchor structure itself. Only frees dynamically allocated fields within the structure.
Usage: Must be called for each trust anchor in anchor_list.buf before freeing anchor_list.buf. Loop through anchors and call for each one.
Warning
Memory leak: Must call this for each trust anchor before freeing anchor_list.buf. Failing to do so will leak memory.

Definition at line 448 of file pem.c.

448 {
449 if (!ta) {
450 return;
451 }
452 xfree(ta->dn.data);
453 switch (ta->pkey.key_type) {
454 case BR_KEYTYPE_RSA:
455 xfree((void *)ta->pkey.key.rsa.n);
456 xfree((void *)ta->pkey.key.rsa.e);
457 break;
458 case BR_KEYTYPE_EC:
459 xfree((void *)ta->pkey.key.ec.q);
460 break;
461 default:
462 SET_ERRNO(ERROR_CRYPTO, "Unknown public key type in CA");
463 break;
464 }
465}

References ERROR_CRYPTO, and SET_ERRNO.

Referenced by read_trust_anchors_from_memory().

◆ get_known_hosts_path()

const char * get_known_hosts_path ( void )

#include <lib/crypto/known_hosts.c>

Get the path to the known_hosts file.

Get known_hosts file path.

Returns the path to the known_hosts file, using the same directory as all other ascii-chat configuration files (get_config_dir()).

PATH RESOLUTION:

  • Unix: $XDG_CONFIG_HOME/ascii-chat/known_hosts or ~/.config/ascii-chat/known_hosts
  • Windows: APPDATA%\ascii-chat\known_hosts
Returns
Pointer to cached known_hosts path (do not free), or NULL on failure
Note
The returned pointer is valid for the lifetime of the program
Returns
Path to known_hosts file (never NULL, cached)

Returns path to known_hosts file, expanding user directory if needed. Path is cached after first call.

Note
File location: Returns ~/.ascii-chat/known_hosts (or equivalent on Windows). Uses expand_path() to resolve user directory.
Path caching: Path is cached after first call to avoid repeated expansion. Cache is freed by known_hosts_destroy().
Platform-specific paths (same directory as config.toml):
  • Unix: $XDG_CONFIG_HOME/ascii-chat/known_hosts if set, otherwise ~/.ascii-chat/known_hosts
  • Windows: APPDATA%\ascii-chat\known_hosts if set, otherwise ~\.ascii-chat\known_hosts
Warning
Path may not exist: Function returns path even if file doesn't exist. File will be created when first entry is added.

Definition at line 59 of file known_hosts.c.

59 {
60 // Return cached path if already determined
61 if (!g_known_hosts_path_cache) {
62 char *config_dir = get_config_dir();
63 if (!config_dir) {
64 log_error("Failed to determine configuration directory for known_hosts");
65 return NULL;
66 }
67 defer(SAFE_FREE(config_dir));
68
69 // Build path: config_dir + "known_hosts"
70 size_t config_len = strlen(config_dir);
71 size_t total_len = config_len + strlen("known_hosts") + 1;
72 char *path = SAFE_MALLOC(total_len, char *);
73 if (!path) {
74 log_error("Failed to allocate memory for known_hosts path");
75 return NULL;
76 }
77
78 safe_snprintf(path, total_len, "%sknown_hosts", config_dir);
79 g_known_hosts_path_cache = path;
80 log_debug("KNOWN_HOSTS: Using path %s", g_known_hosts_path_cache);
81 }
82 return g_known_hosts_path_cache;
83}
#define SAFE_MALLOC(size, cast)
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:293

References get_config_dir(), log_debug, log_error, SAFE_FREE, and SAFE_MALLOC.

Referenced by add_known_host(), check_known_host_no_identity(), crypto_handshake_client_key_exchange(), display_mitm_warning(), prompt_unknown_host(), and remove_known_host().

◆ gpg_agent_connect()

int gpg_agent_connect ( void )

#include <include/ascii-chat/crypto/gpg/agent.h>

Connect to gpg-agent.

Returns
Socket/pipe handle on success, -1 on error

Establishes connection to GPG agent using Assuan protocol. Connects to agent socket/pipe and performs initial handshake.

Note
Connection method:
  • Unix: Connects to Unix domain socket (~/.gnupg/S.gpg-agent or GPG_AGENT_INFO)
  • Windows: Connects to named pipe (\.\pipe\gpg-agent or from GPG_AGENT_INFO)
Socket location:
  • Unix: $GPG_AGENT_INFO or ~/.gnupg/S.gpg-agent
  • Windows: Named pipe from GPG_AGENT_INFO or default pipe
Assuan protocol: After connection, sends initial commands:
  • Receives "OK Pleased to meet you" greeting
  • No additional initialization needed for signing operations
Connection ownership: Caller must call gpg_agent_disconnect() when done. Failing to disconnect will leak socket handles.
Warning
Agent requirement: GPG agent must be running and accessible. Returns -1 if agent is not available (not running, wrong path, etc.).
Socket cleanup: Must call gpg_agent_disconnect() to close socket. Failing to do so will leak file descriptors/handles.

Definition at line 104 of file agent.c.

104 {
105 char agent_path[PLATFORM_MAX_PATH_LENGTH];
106 if (platform_get_gpg_agent_socket(agent_path, sizeof(agent_path)) != 0) {
107 log_error("Failed to get GPG agent path");
108 return -1;
109 }
110
111 log_debug("Connecting to GPG agent at: %s", agent_path);
112
113 // Use platform abstraction for pipe/socket connection
114 pipe_t pipe = platform_pipe_connect(agent_path);
115 if (!platform_pipe_is_valid(pipe)) {
116 log_error("Failed to connect to GPG agent");
117 return -1;
118 }
119
120 // Read initial greeting
121 char response[GPG_AGENT_MAX_RESPONSE];
122 if (read_agent_line(pipe, response, sizeof(response), NULL) != 0) {
123 log_error("Failed to read GPG agent greeting");
124 platform_pipe_close(pipe);
125 return -1;
126 }
127
128 if (!is_ok_response(response)) {
129 log_error("Unexpected GPG agent greeting: %s", response);
130 platform_pipe_close(pipe);
131 return -1;
132 }
133
134 log_debug("Connected to GPG agent successfully");
135
136 // Set loopback pinentry mode to avoid interactive prompts
137 // This allows GPG agent to work in non-interactive environments
138 if (send_agent_command(pipe, "OPTION pinentry-mode=loopback") != 0) {
139 log_warn("Failed to set loopback pinentry mode (continuing anyway)");
140 } else {
141 // Read response for OPTION command
142 if (read_agent_line(pipe, response, sizeof(response), NULL) != 0) {
143 log_warn("Failed to read OPTION command response (continuing anyway)");
144 } else if (is_ok_response(response)) {
145 log_debug("Loopback pinentry mode enabled");
146 } else {
147 log_warn(
148 "Failed to enable loopback pinentry mode: %s (continuing anyway)",
149 response);
150 }
151 }
152
153 return (int)(intptr_t)pipe;
154}
#define GPG_AGENT_MAX_RESPONSE
Definition agent.c:35

References GPG_AGENT_MAX_RESPONSE, log_debug, log_error, and log_warn.

Referenced by ed25519_sign_message(), gpg_agent_is_available(), and gpg_get_public_key().

◆ gpg_agent_disconnect()

void gpg_agent_disconnect ( int sock)

#include <include/ascii-chat/crypto/gpg/agent.h>

Disconnect from gpg-agent.

Parameters
sockSocket/pipe handle from gpg_agent_connect()

Closes connection to GPG agent and releases socket resources. Safe to call with invalid socket (does nothing if sock < 0).

Note
Socket closure: Closes socket handle using platform-specific close function. On Unix, uses close(). On Windows, uses CloseHandle().
Assuan protocol: No goodbye message needed - just closes socket. GPG agent handles disconnections gracefully.
Safe disconnect: Function validates socket handle before closing. Safe to call with -1 or invalid handles.
Warning
Always call this after gpg_agent_connect() to avoid resource leaks.

Definition at line 156 of file agent.c.

156 {
157 if (handle_as_int >= 0) {
158 pipe_t pipe = (pipe_t)(intptr_t)handle_as_int;
159 send_agent_command(pipe, "BYE");
160 platform_pipe_close(pipe);
161 }
162}

Referenced by ed25519_sign_message(), gpg_agent_is_available(), and gpg_get_public_key().

◆ gpg_agent_is_available()

bool gpg_agent_is_available ( void )

#include <include/ascii-chat/crypto/gpg/agent.h>

Check if GPG agent is available.

Returns
true if gpg-agent is running and accessible, false otherwise

Checks if GPG agent is running by attempting to connect and immediately disconnecting. Uses gpg_agent_connect() internally.

Note
Agent detection: Attempts actual connection to verify agent is running. Returns false if connection fails for any reason.
Platform differences:
  • Unix: Checks for socket existence and accessibility (~/.gnupg/S.gpg-agent)
  • Windows: Attempts to connect to named pipe
Connection test: Creates temporary connection and closes it immediately. Does not leave connection open.
Performance: Involves actual socket connection - may be slow if agent is not running. Consider caching result if calling frequently.
Warning
Agent may not be running: Function returns false if agent is not running, socket/pipe doesn't exist, or permissions prevent access.

Definition at line 359 of file agent.c.

359 {
360 int sock = gpg_agent_connect();
361 if (sock < 0) {
362 return false;
363 }
365 return true;
366}
int gpg_agent_connect(void)
Connect to gpg-agent.
Definition agent.c:104
void gpg_agent_disconnect(int handle_as_int)
Disconnect from gpg-agent.
Definition agent.c:156

References gpg_agent_connect(), and gpg_agent_disconnect().

◆ gpg_agent_sign()

int gpg_agent_sign ( int sock,
const char * keygrip,
const uint8_t * message,
size_t message_len,
uint8_t * signature_out,
size_t * signature_len_out )

#include <include/ascii-chat/crypto/gpg/agent.h>

Sign a message using GPG agent.

Parameters
sockSocket/pipe handle from gpg_agent_connect() (must be valid)
keygripGPG keygrip (40-char hex string, must not be NULL)
messageMessage to sign (must not be NULL)
message_lenMessage length (must be > 0)
signature_outOutput buffer for signature (must be >= 64 bytes for Ed25519)
signature_len_outOutput parameter for signature length (must not be NULL)
Returns
0 on success, -1 on error

Signs message using GPG agent Assuan protocol PKSIGN command. Key stays in GPG agent - private key never enters application memory.

Note
Assuan protocol commands:
  1. RESET - Clear any previous state
  2. SIGKEY <keygrip> - Select key to use for signing
  3. SETHASH –hash=sha256 <hex_hash> - Set message hash (SHA-256 of message)
  4. PKSIGN - Perform signature operation
Key selection: Uses keygrip to identify key in agent. Keygrip is 40-char hex string computed from public key material.
Hash algorithm: Uses SHA-256 hash of message for signing. GPG agent expects hex-encoded hash, not raw message.
Signature format: Returns raw Ed25519 signature (64 bytes). Format: R || S (32 bytes each) for Ed25519.
Error handling: Returns -1 on any error:
  • Agent connection lost
  • Key not found in agent (wrong keygrip)
  • Signature operation failed
  • Protocol error (malformed response)
Connection requirement: Requires active connection from gpg_agent_connect(). Does not create or close connection - caller manages connection lifecycle.
Warning
Agent connection: Requires valid socket from gpg_agent_connect(). Returns -1 if socket is invalid or connection is closed.
Key availability: Key must be in GPG agent and identified by keygrip. Returns -1 if key not found or keygrip is invalid.
Buffer size: signature_out must be at least 64 bytes for Ed25519. Function writes up to 64 bytes and sets signature_len_out accordingly.

Definition at line 164 of file agent.c.

166 {
167 if (handle_as_int < 0 || !keygrip || !message || !signature_out ||
168 !signature_len_out) {
169 log_error("Invalid arguments");
170 return -1;
171 }
172
173 pipe_t handle = (pipe_t)(intptr_t)handle_as_int;
174 char response[GPG_AGENT_MAX_RESPONSE];
175
176 // 1. Set the key to use (SIGKEY command)
178 safe_snprintf(sigkey_cmd, sizeof(sigkey_cmd), "SIGKEY %s", keygrip);
179 if (send_agent_command(handle, sigkey_cmd) != 0) {
180 log_error("Failed to send SIGKEY command");
181 return -1;
182 }
183
184 if (read_agent_line(handle, response, sizeof(response), NULL) != 0) {
185 log_error("Failed to read SIGKEY response");
186 return -1;
187 }
188
189 if (!is_ok_response(response)) {
190 log_error("SIGKEY failed: %s", response);
191 return -1;
192 }
193
194 // 2. For EdDSA/Ed25519, GPG agent requires SETHASH with a hash algorithm
195 // GPG agent doesn't support --inquire for SETHASH - the command syntax is:
196 // SETHASH (--hash=<name>)|(<algonumber>) <hexstring>
197 // For Ed25519, we hash the message with SHA512 (algo 10) first
198
199 // Hash the message with SHA512 using libsodium
200 uint8_t hash[crypto_hash_sha512_BYTES];
201 crypto_hash_sha512(hash, message, message_len);
202
203 // Build SETHASH command with SHA512 hash (algo 10)
204 // Format: "SETHASH 10 <128 hex chars for 64-byte SHA512 hash>"
206 int offset = safe_snprintf(sethash_cmd, sizeof(sethash_cmd), "SETHASH 10 ");
207 for (size_t i = 0; i < crypto_hash_sha512_BYTES; i++) {
208 offset +=
209 safe_snprintf(sethash_cmd + offset,
210 sizeof(sethash_cmd) - (size_t)offset, "%02X", hash[i]);
211 }
212
213 log_debug("Sending SETHASH command with SHA512 hash");
214 if (send_agent_command(handle, sethash_cmd) != 0) {
215 log_error("Failed to send SETHASH command");
216 return -1;
217 }
218
219 // Read SETHASH response
220 if (read_agent_line(handle, response, sizeof(response), NULL) != 0) {
221 log_error("Failed to read SETHASH response");
222 return -1;
223 }
224
225 if (!is_ok_response(response)) {
226 log_error("SETHASH failed: %s", response);
227 return -1;
228 }
229
230 // 3. Request signature using PKSIGN
231 if (send_agent_command(handle, "PKSIGN") != 0) {
232 log_error("Failed to send PKSIGN command");
233 return -1;
234 }
235
236 // Read response - skip status/error lines and wait for data line (D ...)
237 // GPG agent sends informational ERR lines that are not fatal (e.g., "Not
238 // implemented") Keep reading until we get the actual signature data
239 bool found_data = false;
240 size_t response_len = 0;
241 for (int attempts = 0; attempts < 20; attempts++) {
242 if (read_agent_line(handle, response, sizeof(response), &response_len) !=
243 0) {
244 log_error("Failed to read PKSIGN response");
245 return -1;
246 }
247
248 log_debug("PKSIGN response line %d (%zu bytes)", attempts + 1,
249 response_len);
250
251 // Skip status lines (S INQUIRE_MAXLEN, etc)
252 if (response[0] == 'S' && response[1] == ' ') {
253 log_debug("Skipping PKSIGN status line: %s", response);
254 continue;
255 }
256
257 // Skip informational ERR lines (GPG agent sends these even on success)
258 // Common ERR codes: 67109141 (IPC cancelled), 67108933 (Not implemented)
259 if (strncmp(response, "ERR", 3) == 0) {
260 log_debug("Skipping PKSIGN error line (informational): %s", response);
261 continue;
262 }
263
264 // Check if it's a data line (D followed by space)
265 if (response[0] == 'D' && response[1] == ' ') {
266 log_debug("Found signature data line");
267 found_data = true;
268 break;
269 }
270
271 // Check for OK (success without data would be unexpected)
272 if (strncmp(response, "OK", 2) == 0) {
273 log_warn("PKSIGN returned OK without data line");
274 continue; // Keep trying in case D line follows
275 }
276
277 // Check if GPG agent is sending another INQUIRE (shouldn't happen)
278 if (strncmp(response, "INQUIRE", 7) == 0) {
279 log_error("Unexpected INQUIRE after PKSIGN: %s", response);
280 return -1;
281 }
282
283 // Unknown response type
284 log_warn("Unexpected PKSIGN response (attempt %d): %s", attempts + 1,
285 response);
286 }
287
288 if (!found_data) {
289 log_error("Expected D line from PKSIGN after %d attempts", 20);
290 return -1;
291 }
292
293 // Assuan escapes binary bytes as %HH. Decode before reading canonical
294 // S-expression fields.
296 size_t decoded_len = 0;
297 for (size_t input = 2; input < response_len; ++input) {
298 if (decoded_len == sizeof(decoded)) {
299 log_error("GPG agent signature response exceeds buffer");
300 return -1;
301 }
302 if (response[input] == '%') {
303 if (response_len - input < 3 ||
304 !isxdigit((unsigned char)response[input + 1]) ||
305 !isxdigit((unsigned char)response[input + 2])) {
306 log_error("Invalid percent escape in GPG agent signature");
307 return -1;
308 }
309 char hex[3] = {response[input + 1], response[input + 2], 0};
310 decoded[decoded_len++] = (uint8_t)strtoul(hex, NULL, 16);
311 input += 2;
312 } else {
313 decoded[decoded_len++] = (uint8_t)response[input];
314 }
315 }
316 static const char prefix[] = "(7:sig-val(5:eddsa(1:r32:";
317 static const char separator[] = ")(1:s32:";
318 static const char suffix[] = ")))";
319 const size_t prefix_len = sizeof(prefix) - 1;
320 const size_t separator_len = sizeof(separator) - 1;
321 const size_t expected_len =
322 prefix_len + 32 + separator_len + 32 + sizeof(suffix) - 1;
323 if (decoded_len != expected_len || memcmp(decoded, prefix, prefix_len) != 0 ||
324 memcmp(decoded + prefix_len + 32, separator, separator_len) != 0 ||
325 memcmp(decoded + expected_len - (sizeof(suffix) - 1), suffix,
326 sizeof(suffix) - 1) != 0) {
327 log_error("Invalid Ed25519 signature S-expression from GPG agent");
328 return -1;
329 }
330 memcpy(signature_out, decoded + prefix_len, ED25519_SIGNATURE_PART_SIZE);
331 memcpy(signature_out + ED25519_SIGNATURE_PART_SIZE,
332 decoded + prefix_len + 32 + separator_len,
334 *signature_len_out = 64;
335
336 // DEBUG: Print signature in hex
337 char sig_hex[HEX_STRING_SIZE_64];
338 for (int i = 0; i < 64; i++) {
339 safe_snprintf(sig_hex + i * 2, 3, "%02x", (unsigned char)signature_out[i]);
340 }
341 sig_hex[128] = '\0';
342 log_debug("Extracted signature (64 bytes): %s", sig_hex);
343
344 // Read final OK
345 if (read_agent_line(handle, response, sizeof(response), &response_len) != 0) {
346 log_error("Failed to read final PKSIGN response");
347 return -1;
348 }
349
350 if (!is_ok_response(response)) {
351 log_error("PKSIGN final response not OK: %s", response);
352 return -1;
353 }
354
355 log_debug("Successfully signed message with GPG agent");
356 return 0;
357}
#define CRYPTO_GPG_AGENT_SIGKEY_CMD_BUFFER_SIZE
Definition agent.c:8
#define CRYPTO_GPG_AGENT_SETHASH_CMD_BUFFER_SIZE
Definition agent.c:9
#define ED25519_SIGNATURE_PART_SIZE
Definition sizes.h:7
#define HEX_STRING_SIZE_64
Hex string size for 64-byte values (128 hex chars + null terminator).
Definition sizes.h:166

References CRYPTO_GPG_AGENT_SETHASH_CMD_BUFFER_SIZE, CRYPTO_GPG_AGENT_SIGKEY_CMD_BUFFER_SIZE, ED25519_SIGNATURE_PART_SIZE, GPG_AGENT_MAX_RESPONSE, HEX_STRING_SIZE_64, log_debug, log_error, and log_warn.

Referenced by ed25519_sign_message().

◆ gpg_get_public_key()

int gpg_get_public_key ( const char * key_id,
uint8_t * public_key_out,
char * keygrip_out )

#include <include/ascii-chat/crypto/gpg/export.h>

Get public key from GPG keyring by key ID.

Parameters
key_idGPG key ID (8/16/40-char hex string, must not be NULL)
public_key_outOutput buffer for 32-byte Ed25519 public key (must not be NULL)
keygrip_outOutput buffer for 40-char keygrip + null terminator (can be NULL if not needed)
Returns
0 on success, -1 on error

Retrieves Ed25519 public key from GPG keyring using gpg --export command. Parses OpenPGP packet format to extract raw 32-byte Ed25519 public key.

Note
Key ID format: Accepts short (8-char), long (16-char), or full (40-char) hex key IDs. Prefix "0x" is optional and will be added automatically if missing. Examples: "7FE90A79F2E80ED3", "0x7FE90A79F2E80ED3", "EDDAE1DA7360D7F4"
Export method: Uses gpg --export 0x<KEY_ID> to export public key. Output is in binary OpenPGP packet format, which is then parsed.
OpenPGP parsing: Parses OpenPGP packet structure to locate Ed25519 public key packet. Extracts 32-byte Ed25519 public key material from packet (algorithm ID 22). Skips 0x40 prefix byte if present (standard OpenPGP MPI format).
Keygrip extraction: If keygrip_out is not NULL, extracts keygrip using gpg --with-keygrip --list-keys. Keygrip is 40-char hex string that identifies key in GPG agent. Useful for subsequent gpg_agent_sign() operations.
Key validation: Validates that key is Ed25519 (algorithm 22 in OpenPGP). Returns error if key is RSA, ECDSA, or other unsupported algorithm.
Buffer requirements:
  • public_key_out: Must be at least 32 bytes
  • keygrip_out: Must be at least 41 bytes (40 hex chars + null terminator) if provided
Error conditions: Returns -1 if:
  • Key ID not found in keyring
  • Key is not Ed25519 (RSA/ECDSA not supported)
  • gpg binary not found in PATH
  • OpenPGP packet parsing fails
  • Key export produces empty output
Warning
GPG binary required: Requires gpg binary in PATH. Returns -1 if GPG is not installed or not accessible.
Ed25519 only: Only Ed25519 keys are supported (OpenPGP algorithm 22). RSA/ECDSA keys will return error.
Key ID must exist: Key must exist in local GPG keyring. Returns -1 if key is not found (check with gpg --list-keys <KEY_ID>).

Definition at line 262 of file export.c.

263 {
264 if (!key_id || !public_key_out) {
265 log_error("Invalid arguments");
266 return -1;
267 }
268
269 // SECURITY: Validate key_id to prevent command injection
270 // GPG key IDs should be hexadecimal (0-9, a-f, A-F)
271 if (!validate_shell_safe(key_id, NULL)) {
272 log_error("Invalid GPG key ID format - contains unsafe characters: %s",
273 key_id);
274 return -1;
275 }
276
277 // Additional validation: ensure key_id is hex alphanumeric
278 for (size_t i = 0; key_id[i] != '\0'; i++) {
279 if (!isxdigit((unsigned char)key_id[i])) {
280 log_error("Invalid GPG key ID format - must be hexadecimal: %s", key_id);
281 return -1;
282 }
283 }
284
285 // Escape key_id for safe use in shell command (single quotes)
286 char escaped_key_id[BUFFER_SIZE_MEDIUM];
287 if (!escape_shell_single_quotes(key_id, escaped_key_id,
288 sizeof(escaped_key_id))) {
289 log_error("Failed to escape GPG key ID for shell command");
290 return -1;
291 }
292
293 // Use gpg to list the key and get the keygrip
294 char cmd[BUFFER_SIZE_LARGE];
295 safe_snprintf(cmd, sizeof(cmd),
296 "gpg --list-keys --with-keygrip --with-colons "
297 "0x%s " PLATFORM_SHELL_NULL_REDIRECT,
298 escaped_key_id);
299
300 FILE *fp = NULL;
301 if (platform_popen("gpg_export", cmd, "r", &fp) != ASCIICHAT_OK || !fp) {
302 log_error("Failed to run gpg command - GPG may not be installed");
303#ifdef _WIN32
304 log_error("To install GPG on Windows, download Gpg4win from:");
305 log_error(" https://www.gpg4win.org/download.html");
306#elif defined(__APPLE__)
307 log_error("To install GPG on macOS, use Homebrew:");
308 log_error(" brew install gnupg");
309#else
310 log_error("To install GPG on Linux:");
311 log_error(" Debian/Ubuntu: sudo apt-get install gnupg");
312 log_error(" Fedora/RHEL: sudo dnf install gnupg2");
313 log_error(" Arch Linux: sudo pacman -S gnupg");
314 log_error(" Alpine Linux: sudo apk add gnupg");
315#endif
316 return -1;
317 }
318
319 char line[BUFFER_SIZE_XLARGE];
320 char found_keygrip[CRYPTO_GPG_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE] = {0};
321 bool found_key = false;
322
323 // Parse gpg output
324 // Format: pub:..., grp:::::::::<keygrip>:
325 while (fgets(line, sizeof(line), fp)) {
326 if (strncmp(line, "pub:", 4) == 0) {
327 // Found the public key line
328 found_key = true;
329 } else if (found_key && strncmp(line, "grp:", 4) == 0) {
330 // Extract keygrip using PCRE2 regex
331 // Format: grp:::::::::D52FF935FBA59609EE65E1685287828242A1EA1A:
332 char *keygrip_extracted = NULL;
333
334 if (crypto_regex_extract_gpg_keygrip(line, &keygrip_extracted)) {
335 // Successfully extracted keygrip
336 SAFE_STRNCPY(found_keygrip, keygrip_extracted, sizeof(found_keygrip));
337 if (keygrip_out) {
338 SAFE_STRNCPY(keygrip_out, found_keygrip, 41);
339 }
340 SAFE_FREE(keygrip_extracted);
341 } else {
342 // Fallback to manual parsing if regex fails
343 const char *grp_start = line + 4;
344 int colon_count = 0;
345 while (*grp_start && colon_count < 8) {
346 if (*grp_start == ':') {
347 colon_count++;
348 }
349 grp_start++;
350 }
351
352 if (colon_count == 8) {
353 const char *grp_end = strchr(grp_start, ':');
354 if (grp_end) {
355 size_t grp_len = grp_end - grp_start;
356 if (grp_len < sizeof(found_keygrip)) {
357 memcpy(found_keygrip, grp_start, grp_len);
358 found_keygrip[grp_len] = '\0';
359
360 if (keygrip_out) {
361 SAFE_STRNCPY(keygrip_out, found_keygrip, 41);
362 }
363 }
364 }
365 }
366 }
367 break;
368 }
369 }
370
371 platform_pclose(&fp);
372
373 if (!found_key || strlen(found_keygrip) == 0) {
374 log_error("Could not find GPG key with ID: %s", key_id);
375 return -1;
376 }
377
378 log_debug("Found keygrip for key %s: %s", key_id, found_keygrip);
379
380 // Try to use GPG agent API to read the public key directly via READKEY
381 // command
382 int agent_sock = gpg_agent_connect();
383 if (agent_sock < 0) {
384 log_debug("GPG agent not available, falling back to gpg --export for "
385 "public key extraction");
386 // Fallback: Use gpg --export to get the public key
387 int export_result = gpg_export_public_key(key_id, public_key_out);
388 if (export_result == 0) {
389 log_debug("Successfully extracted public key using fallback method");
390 } else {
391 log_error("Fallback public key extraction failed for key ID: %s", key_id);
392 }
393 return export_result;
394 }
395
396 // Send READKEY command with keygrip to get the public key S-expression
397 char readkey_cmd[BUFFER_SIZE_SMALL];
398 safe_snprintf(readkey_cmd, sizeof(readkey_cmd), "READKEY %s\n",
399 found_keygrip);
400
401 // Cast agent_sock back to pipe_t (gpg_agent_connect returns pipe_t cast to
402 // int for portability)
403 pipe_t agent_pipe = (pipe_t)(intptr_t)agent_sock;
404 ssize_t bytes_written = platform_pipe_write(
405 agent_pipe, (const unsigned char *)readkey_cmd, strlen(readkey_cmd));
406 if (bytes_written != (ssize_t)strlen(readkey_cmd)) {
407 log_error("Failed to send READKEY command to GPG agent");
408 gpg_agent_disconnect(agent_sock);
409 return -1;
410 }
411
412 // Read the response (public key S-expression)
413 char response[BUFFER_SIZE_XXXLARGE];
414 memset(response, 0, sizeof(response));
415 ssize_t bytes_read = platform_pipe_read(agent_pipe, (unsigned char *)response,
416 sizeof(response) - 1);
417
418 gpg_agent_disconnect(agent_sock);
419
420 if (bytes_read <= 0) {
421 log_error("Failed to read READKEY response from GPG agent");
422 return -1;
423 }
424
425 // Assuan data lines escape %, CR and LF, including bytes inside the
426 // S-expression.
427 size_t decoded = 0;
428 for (size_t i = 0; i < (size_t)bytes_read; ++i) {
429 if (response[i] == '%' && i + 2 < (size_t)bytes_read &&
430 isxdigit((unsigned char)response[i + 1]) &&
431 isxdigit((unsigned char)response[i + 2])) {
432 unsigned char high =
433 (unsigned char)tolower((unsigned char)response[i + 1]);
434 unsigned char low =
435 (unsigned char)tolower((unsigned char)response[i + 2]);
436 high = high <= '9' ? high - '0' : high - 'a' + 10;
437 low = low <= '9' ? low - '0' : low - 'a' + 10;
438 response[decoded++] = (char)((high << 4) | low);
439 i += 2;
440 } else {
441 response[decoded++] = response[i];
442 }
443 }
444 response[decoded] = '\0';
445
446 // Parse the S-expression to extract Ed25519 public key (q value)
447 // GPG agent returns binary S-expressions in format:
448 // (1:q<length>:<binary-data>) Example: (1:q33:<33-bytes>) where first byte is
449 // 0x40 (Ed25519 prefix), then 32-byte key
450 const char *q_marker = strstr(response, "(1:q");
451 if (!q_marker) {
452 log_warn("Failed to find public key (1:q) in GPG agent READKEY response, "
453 "trying gpg --export fallback");
454 log_debug("Response was: %.*s", (int)(bytes_read < 200 ? bytes_read : 200),
455 response);
456 gpg_agent_disconnect(agent_sock);
457
458 // Fallback: Use gpg --export for public-only keys
459 int export_result = gpg_export_public_key(key_id, public_key_out);
460 if (export_result == 0) {
461 log_debug(
462 "Successfully extracted public key using gpg --export fallback");
463 } else {
464 log_error("Fallback public key extraction failed for key ID: %s", key_id);
465 }
466 return export_result;
467 }
468
469 // Skip "(1:q" to get to the length field
470 const char *len_start = q_marker + 4;
471
472 // Parse the length (e.g., "33:")
473 const char *colon = strchr(len_start, ':');
474 if (!colon) {
475 log_error("Malformed S-expression: missing colon after length");
476 return -1;
477 }
478
479 size_t key_len = strtoul(len_start, NULL, 10);
480 if (key_len != 33) {
481 log_error("Unexpected Ed25519 public key length: %zu bytes (expected 33)",
482 key_len);
483 return -1;
484 }
485
486 // Skip the colon to get to the binary data
487 const unsigned char *binary_start = (const unsigned char *)(colon + 1);
488 if ((size_t)(binary_start - (const unsigned char *)response) + key_len >
489 decoded) {
490 log_error("Truncated Ed25519 public key in GPG agent response");
491 return -1;
492 }
493
494 // Ed25519 public keys in GPG format have a 0x40 prefix byte, then 32 bytes of
495 // actual key
496 if (binary_start[0] != 0x40) {
497 log_error("Invalid Ed25519 public key prefix: 0x%02x (expected 0x40)",
498 binary_start[0]);
499 return -1;
500 }
501
502 // Copy the 32-byte public key (skip the 0x40 prefix)
503 memcpy(public_key_out, binary_start + 1, ED25519_PUBLIC_KEY_SIZE);
504
505 log_debug("Extracted Ed25519 public key from GPG agent via READKEY command");
506 return 0;
507}
#define CRYPTO_GPG_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE
Definition export.c:8
#define BUFFER_SIZE_XXXLARGE
Extra extra extra large buffer size (8192 bytes).
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_STRNCPY(dst, src, size)
bool escape_shell_single_quotes(const char *str, char *out_buffer, size_t out_buffer_size)
Validate that a string contains only safe characters for shell commands.
atomic_t bytes_written
Definition mmap.c:47
bool crypto_regex_extract_gpg_keygrip(const char *line, char **keygrip_out)
Definition regex.c:277
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:38
int platform_popen(const char *name, const char *command, const char *mode, FILE **out_stream)
int platform_pclose(FILE **stream_ptr)

References ASCIICHAT_OK, BUFFER_SIZE_LARGE, BUFFER_SIZE_MEDIUM, BUFFER_SIZE_SMALL, BUFFER_SIZE_XLARGE, BUFFER_SIZE_XXXLARGE, bytes_written, CRYPTO_GPG_EXPORT_FOUND_KEYGRIP_BUFFER_SIZE, crypto_regex_extract_gpg_keygrip(), ED25519_PUBLIC_KEY_SIZE, escape_shell_single_quotes(), gpg_agent_connect(), gpg_agent_disconnect(), log_debug, log_error, log_warn, platform_pclose(), platform_popen(), SAFE_FREE, and SAFE_STRNCPY.

Referenced by extract_ed25519_from_gpg(), and parse_private_key().

◆ gpg_sign_detached_ed25519()

int gpg_sign_detached_ed25519 ( const char * key_id,
const uint8_t * message,
size_t message_len,
uint8_t signature_out[ED25519_SIGNATURE_SIZE] )

#include <include/ascii-chat/crypto/gpg/signing.h>

Sign message with GPG and extract raw Ed25519 signature.

Parameters
key_idGPG key ID (8/16/40-char hex string, must not be NULL)
messageMessage to sign (must not be NULL)
message_lenMessage length in bytes (must be > 0)
signature_outOutput buffer for 64-byte Ed25519 signature (must not be NULL)
Returns
0 on success, -1 on error

Signs message using gpg --detach-sign, then extracts raw 64-byte Ed25519 signature from OpenPGP packet format. Returns signature in libsodium-compatible format (R||S).

Note
Key ID format: Accepts short (8-char), long (16-char), or full (40-char) hex key IDs. Prefix "0x" is optional and will be added automatically if missing.
Signing method: Uses gpg --detach-sign --local-user 0x<KEY_ID> command. Then parses OpenPGP output to extract raw signature bytes.
OpenPGP parsing: Parses binary OpenPGP signature packet to locate signature data. Extracts raw Ed25519 signature (R||S format, 64 bytes total). Skips packet headers and metadata to get pure signature bytes.
Output format: Returns raw Ed25519 signature in libsodium format. Format: R || S (32 bytes R + 32 bytes S = 64 bytes total). Compatible with crypto_sign_verify_detached() from libsodium.
Fixed length: Ed25519 signatures are always exactly 64 bytes. No length parameter needed - signature_out is always fully written.
Use case: Prefer this over gpg_sign_with_key() when you need raw signature. Useful for protocol implementations that expect raw Ed25519 signatures rather than OpenPGP-wrapped signatures.
Comparison with gpg_sign_with_key():
Key passphrase handling:
  • If key is encrypted, GPG may prompt for passphrase interactively
  • Use gpg-agent for password-free signing (recommended)
  • Or set $ASCII_CHAT_KEY_PASSWORD environment variable
Buffer requirements:
  • signature_out: Must be exactly 64 bytes (Ed25519 signature size)
Error conditions: Returns -1 if:
  • Key ID not found in keyring
  • Key is not Ed25519 (RSA/ECDSA not supported)
  • gpg binary not found in PATH
  • Signing operation fails (wrong passphrase, key expired, etc.)
  • OpenPGP packet parsing fails
  • Signature extraction fails (unexpected packet format)
Warning
GPG binary required: Requires gpg binary in PATH. Returns -1 if GPG is not installed or not accessible.
Ed25519 only: Only Ed25519 keys are supported (OpenPGP algorithm 22). RSA/ECDSA keys will return error.
Buffer size: signature_out must be exactly 64 bytes. Function always writes exactly 64 bytes on success.
Key must exist: Key must exist in local GPG keyring. Returns -1 if key is not found (check with gpg --list-keys <KEY_ID>).

Definition at line 155 of file signing.c.

157 {
158 log_debug("Signing with key ID %s (fallback mode)", key_id);
159
160 // Get OpenPGP signature packet from gpg --detach-sign
161 uint8_t openpgp_signature[GPG_SIGNATURE_PACKET_CAPACITY];
162 size_t openpgp_len = 0;
163
164 int result = gpg_sign_with_key(key_id, message, message_len,
165 openpgp_signature, &openpgp_len);
166 if (result != 0) {
167 log_error("GPG detached signing failed for key %s", key_id);
168 return -1;
169 }
170
171 log_debug("gpg_sign_with_key returned %zu bytes", openpgp_len);
172
173 if (openpgp_len < 10) {
174 log_error("GPG signature too short: %zu bytes", openpgp_len);
175 return -1;
176 }
177
178 log_debug("Parsing OpenPGP signature packet (%zu bytes) to extract Ed25519 "
179 "signature",
180 openpgp_len);
181
182 // Parse OpenPGP signature packet format
183 // Reference: RFC 4880 Section 5.2 (Signature Packet)
184 // Format: [header][version][type][algo][hash-algo][...][signature-data]
185 size_t offset = 0;
186
187 // Parse packet header
188 uint8_t tag = openpgp_signature[offset++];
189 size_t packet_len = 0;
190
191 if ((tag & 0x40) == 0) {
192 // Old format packet
193 uint8_t length_type = tag & 0x03;
194 if (length_type == 0) {
195 packet_len = openpgp_signature[offset++];
196 } else if (length_type == 1) {
197 packet_len =
198 (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
199 offset += 2;
200 } else if (length_type == 2) {
201 packet_len = (openpgp_signature[offset] << 24) |
202 (openpgp_signature[offset + 1] << 16) |
203 (openpgp_signature[offset + 2] << 8) |
204 openpgp_signature[offset + 3];
205 offset += 4;
206 } else {
207 log_error("Unsupported old-format packet length type: %d", length_type);
208 return -1;
209 }
210 } else {
211 // New format packet
212 uint8_t length_byte = openpgp_signature[offset++];
213 if (length_byte < 192) {
214 packet_len = length_byte;
215 } else if (length_byte < 224) {
216 packet_len =
217 ((length_byte - 192) << 8) + openpgp_signature[offset++] + 192;
218 } else if (length_byte == 255) {
219 packet_len = (openpgp_signature[offset] << 24) |
220 (openpgp_signature[offset + 1] << 16) |
221 (openpgp_signature[offset + 2] << 8) |
222 openpgp_signature[offset + 3];
223 offset += 4;
224 } else {
225 log_error("Unsupported new-format packet length encoding: %d",
226 length_byte);
227 return -1;
228 }
229 }
230
231 if (offset + packet_len > openpgp_len) {
232 log_error("Packet length exceeds signature size: %zu + %zu > %zu", offset,
233 packet_len, openpgp_len);
234 return -1;
235 }
236
237 log_debug("Signature packet: offset=%zu, length=%zu", offset, packet_len);
238
239 // Parse signature packet body
240 // Skip: version (1), sig_type (1), pub_algo (1), hash_algo (1)
241 if (offset + 4 > openpgp_len) {
242 log_error("Signature packet too short for header");
243 return -1;
244 }
245
246 uint8_t version = openpgp_signature[offset++];
247 uint8_t sig_type = openpgp_signature[offset++];
248 uint8_t pub_algo = openpgp_signature[offset++];
249 uint8_t hash_algo = openpgp_signature[offset++];
250
251 log_debug("Signature: version=%d, type=%d, algo=%d, hash=%d", version,
252 sig_type, pub_algo, hash_algo);
253
254 // Verify algorithm is Ed25519 (22 = EdDSA)
255 if (pub_algo != 22) {
256 log_error("Expected EdDSA algorithm (22), got %d", pub_algo);
257 return -1;
258 }
259
260 // For v4 signatures: skip hashed subpackets
261 if (version == 4) {
262 if (offset + 2 > openpgp_len) {
263 log_error("Cannot read hashed subpacket length");
264 return -1;
265 }
266 uint16_t hashed_len =
267 (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
268 offset += 2;
269 offset += hashed_len; // Skip hashed subpackets
270
271 if (offset + 2 > openpgp_len) {
272 log_error("Cannot read unhashed subpacket length");
273 return -1;
274 }
275 uint16_t unhashed_len =
276 (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
277 offset += 2;
278 offset += unhashed_len; // Skip unhashed subpackets
279
280 // Skip left 16 bits of signed hash value
281 if (offset + 2 > openpgp_len) {
282 log_error("Cannot read hash left bits");
283 return -1;
284 }
285 offset += 2;
286 }
287
288 // Now we're at the signature data (MPI format for Ed25519)
289 // Ed25519 signature is: r (32 bytes) || s (32 bytes) = 64 bytes total
290 // In OpenPGP, each MPI is encoded as: [2-byte bit count][data]
291
292 if (offset + 2 > openpgp_len) {
293 log_error("Cannot read MPI bit count for R");
294 return -1;
295 }
296
297 uint16_t r_bits =
298 (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
299 offset += 2;
300 size_t r_bytes = (r_bits + 7) / 8;
301
302 log_debug("R: %d bits (%zu bytes)", r_bits, r_bytes);
303
304 if (r_bytes == 0 || r_bytes > 32) {
305 log_error("Expected a 1-32 byte R value, got %zu bytes", r_bytes);
306 return -1;
307 }
308
309 if (offset + r_bytes > openpgp_len) {
310 log_error("R value exceeds packet size");
311 return -1;
312 }
313
314 // OpenPGP MPIs omit leading zero bytes; raw signatures retain fixed-width
315 // components.
316 memset(signature_out, 0, ED25519_SIGNATURE_SIZE);
317 memcpy(signature_out + 32 - r_bytes, &openpgp_signature[offset], r_bytes);
318 offset += r_bytes;
319
320 // Read S value
321 if (offset + 2 > openpgp_len) {
322 log_error("Cannot read MPI bit count for S");
323 return -1;
324 }
325
326 uint16_t s_bits =
327 (openpgp_signature[offset] << 8) | openpgp_signature[offset + 1];
328 offset += 2;
329 size_t s_bytes = (s_bits + 7) / 8;
330
331 log_debug("S: %d bits (%zu bytes)", s_bits, s_bytes);
332
333 if (s_bytes == 0 || s_bytes > 32) {
334 log_error("Expected a 1-32 byte S value, got %zu bytes", s_bytes);
335 return -1;
336 }
337
338 if (offset + s_bytes > openpgp_len) {
339 log_error("S value exceeds packet size");
340 return -1;
341 }
342
343 memcpy(signature_out + 64 - s_bytes, &openpgp_signature[offset], s_bytes);
344
345 log_debug(
346 "Successfully extracted 64-byte Ed25519 signature from OpenPGP packet");
347
348 // Debug: Log signature components
350 for (int i = 0; i < 32; i++) {
351 safe_snprintf(hex_r + i * 2, 3, "%02x", signature_out[i]);
352 safe_snprintf(hex_s + i * 2, 3, "%02x", signature_out[i + 32]);
353 }
354 hex_r[64] = hex_s[64] = '\0';
355 log_debug("Signature R (first 32 bytes): %s", hex_r);
356 log_debug("Signature S (last 32 bytes): %s", hex_s);
357
358 return 0;
359}
unsigned short uint16_t
int gpg_sign_with_key(const char *key_id, const uint8_t *message, size_t message_len, uint8_t *signature_out, size_t *signature_len_out)
Sign a message using GPG key (via gpg –detach-sign).
Definition signing.c:47
#define CRYPTO_GPG_SIGNING_HEX_S_BUFFER_SIZE
Definition signing.c:9
#define ED25519_SIGNATURE_SIZE
Ed25519 signature size in bytes.
Definition sizes.h:42
#define GPG_SIGNATURE_PACKET_CAPACITY
Definition sizes.h:4
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:163

References CRYPTO_GPG_SIGNING_HEX_S_BUFFER_SIZE, ED25519_SIGNATURE_SIZE, gpg_sign_with_key(), GPG_SIGNATURE_PACKET_CAPACITY, HEX_STRING_SIZE_32, log_debug, and log_error.

Referenced by ed25519_sign_message().

◆ gpg_sign_with_key()

int gpg_sign_with_key ( const char * key_id,
const uint8_t * message,
size_t message_len,
uint8_t * signature_out,
size_t * signature_len_out )

#include <include/ascii-chat/crypto/gpg/signing.h>

Sign a message using GPG key and return OpenPGP signature.

Parameters
key_idGPG key ID (8/16/40-char hex string, must not be NULL)
messageMessage to sign (must not be NULL)
message_lenMessage length in bytes (must be > 0)
signature_outOutput buffer for OpenPGP signature (must be >= 512 bytes)
signature_len_outOutput parameter for actual signature length (must not be NULL)
Returns
0 on success, -1 on error

Signs message using gpg --detach-sign and returns full OpenPGP signature packet. Signature is in binary OpenPGP format and includes packet headers.

Note
Key ID format: Accepts short (8-char), long (16-char), or full (40-char) hex key IDs. Prefix "0x" is optional and will be added automatically if missing. Examples: "7FE90A79F2E80ED3", "0x7FE90A79F2E80ED3", "EDDAE1DA7360D7F4"
Signing method: Uses gpg --detach-sign --local-user 0x<KEY_ID> command. Creates detached signature (signature separate from message).
Output format: Returns binary OpenPGP signature packet (RFC 4880). Signature includes packet headers and metadata beyond raw signature data. Typical size: 150-200 bytes for Ed25519 signatures.
Variable length: OpenPGP format means signature length varies. Always check signature_len_out to know actual signature length. Buffer must be at least 512 bytes to accommodate various key types.
GPG interaction: Executes gpg as subprocess and reads output. Signature is read from GPG's stdout in binary format.
Key passphrase handling:
  • If key is encrypted, GPG may prompt for passphrase interactively
  • Use gpg-agent for password-free signing (recommended)
  • Or set $ASCII_CHAT_KEY_PASSWORD environment variable
Buffer requirements:
  • signature_out: Must be at least 512 bytes
  • signature_len_out: Will be set to actual signature length (typically 150-200 bytes)
Error conditions: Returns -1 if:
  • Key ID not found in keyring
  • Key is not Ed25519 (RSA/ECDSA not supported)
  • gpg binary not found in PATH
  • Signing operation fails (wrong passphrase, key expired, etc.)
  • Output buffer too small (< 512 bytes)
Warning
GPG binary required: Requires gpg binary in PATH. Returns -1 if GPG is not installed or not accessible.
Ed25519 only: Only Ed25519 keys are supported (OpenPGP algorithm 22). RSA/ECDSA keys will return error.
Buffer size: signature_out must be at least 512 bytes. Smaller buffers may cause buffer overflow or signature truncation.
Key must exist: Key must exist in local GPG keyring. Returns -1 if key is not found (check with gpg --list-keys <KEY_ID>).

Sign a message using GPG key and return OpenPGP signature.

This function uses gpg --detach-sign which internally uses gpg-agent, so no passphrase prompt if the key is cached in the agent.

Parameters
key_idGPG key ID (e.g., "7FE90A79F2E80ED3")
messageMessage to sign
message_lenMessage length
signature_outOutput buffer for signature (caller must provide at least 512 bytes)
signature_len_outActual signature length written
Returns
0 on success, -1 on error

Definition at line 47 of file signing.c.

49 {
50 if (!key_id || !message || message_len == 0 || !signature_out ||
51 !signature_len_out) {
52 log_error("Invalid parameters");
53 return -1;
54 }
55
56 char msg_path[PLATFORM_MAX_PATH_LENGTH];
57 char sig_path[PLATFORM_MAX_PATH_LENGTH];
58 int msg_fd = -1;
59 int sig_fd = -1;
60 int result = -1;
61
62 // Create temp files using platform abstraction
63 if (platform_create_temp_file(msg_path, sizeof(msg_path), "asciichat_msg",
64 &msg_fd) != 0) {
65 log_error("Failed to create temp message file");
66 return -1;
67 }
68
69 if (platform_create_temp_file(sig_path, sizeof(sig_path), "asciichat_sig",
70 &sig_fd) != 0) {
71 log_error("Failed to create temp signature file");
72 platform_delete_temp_file(msg_path);
73 return -1;
74 }
75
76 // Close signature file descriptor (will be created by gpg)
77 if (sig_fd >= 0) {
78 close(sig_fd);
79 }
80 platform_delete_temp_file(sig_path); // Remove it so gpg can create it fresh
81
82 // Write message to temp file
83 ssize_t written = write(msg_fd, message, (unsigned int)message_len);
84 close(msg_fd);
85 msg_fd = -1;
86
87 if (written != (ssize_t)message_len) {
88 log_error("Failed to write message to temp file");
89 goto cleanup;
90 }
91
92 // Escape key ID for shell command (prevent injection)
94 if (!escape_path_for_shell(key_id, escaped_key_id, sizeof(escaped_key_id))) {
95 log_error("Failed to escape GPG key ID for shell command");
96 goto cleanup;
97 }
98
99 // Call gpg --detach-sign
100 // Use gpg with --detach-sign and --output for safe subprocess execution
101 const char *argv[] = {
102 "gpg", "--local-user", escaped_key_id, "--detach-sign",
103 "--output", sig_path, msg_path, NULL};
104
105 // Note: Don't log the full command as it may contain sensitive key material
106 log_debug("Signing with GPG key 0x%s", escaped_key_id);
107 int status = 0;
108 LOG_IO("gpg", {
109 status = platform_execute_subprocess("gpg", argv, NULL, 0, NULL, NULL);
110 });
111 if (status != 0) {
112 log_error("GPG signing failed (exit code %d)", status);
113 goto cleanup;
114 }
115
116 // Read signature file
117 FILE *sig_fp = platform_fopen("file_stream", sig_path, "rb");
118 if (!sig_fp) {
119 log_error("Failed to open signature file: %s", SAFE_STRERROR(errno));
120 goto cleanup;
121 }
122
123 fseek(sig_fp, 0, SEEK_END);
124 long sig_size = ftell(sig_fp);
125 fseek(sig_fp, 0, SEEK_SET);
126
127 if (sig_size <= 0 || sig_size > 512) {
128 log_error("Invalid signature size: %ld bytes", sig_size);
129 fclose(sig_fp);
130 goto cleanup;
131 }
132
133 size_t bytes_read = fread(signature_out, 1, sig_size, sig_fp);
134 fclose(sig_fp);
135
136 if (bytes_read != (size_t)sig_size) {
137 log_error("Failed to read signature file");
138 goto cleanup;
139 }
140
141 *signature_len_out = sig_size;
142 log_debug("GPG signature created successfully (%zu bytes)",
143 *signature_len_out);
144 result = 0;
145
146cleanup:
147 if (msg_fd >= 0) {
148 close(msg_fd);
149 }
150 platform_delete_temp_file(msg_path);
151 platform_delete_temp_file(sig_path);
152 return result;
153}
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define SAFE_STRERROR(errnum)
bool escape_path_for_shell(const char *path, char *out_buffer, size_t out_buffer_size)
Check if a string needs shell quoting (contains spaces or special chars).
#define LOG_IO(prefix, block)
Definition io.h:106
#define CRYPTO_GPG_SIGNING_ESCAPED_KEY_ID_BUFFER_SIZE
Definition signing.c:8
int platform_execute_subprocess(const char *executable, const char **argv, char *output_buffer, size_t output_size, bool(*cancel)(void *), void *data)
Definition system.c:35

References CRYPTO_GPG_SIGNING_ESCAPED_KEY_ID_BUFFER_SIZE, escape_path_for_shell(), log_debug, log_error, LOG_IO, platform_execute_subprocess(), platform_fopen(), and SAFE_STRERROR.

Referenced by gpg_sign_detached_ed25519(), and gpg_verify_detached_ed25519().

◆ gpg_verify_detached_ed25519()

int gpg_verify_detached_ed25519 ( const char * key_id,
const uint8_t * message,
size_t message_len,
const uint8_t signature[ED25519_SIGNATURE_SIZE] )

#include <include/ascii-chat/crypto/gpg/verification.h>

Verify Ed25519 signature using GPG binary.

Parameters
key_idGPG key ID to use for verification (8/16/40-char hex, must not be NULL)
messageMessage that was signed (must not be NULL)
message_lenMessage length in bytes (must be > 0)
signature64-byte Ed25519 signature (must not be NULL)
Returns
0 on success (valid signature), -1 on error (invalid signature or error)

Verifies raw Ed25519 signature using gpg --verify command. Converts raw signature to OpenPGP format, then uses GPG binary for verification.

Note
Key ID format: Accepts short (8-char), long (16-char), or full (40-char) hex key IDs. Prefix "0x" is optional and will be added automatically if missing. Examples: "7FE90A79F2E80ED3", "0x7FE90A79F2E80ED3", "EDDAE1DA7360D7F4"
Verification method: Uses gpg --verify command on converted OpenPGP signature. Checks both cryptographic validity and key trust status.
Signature format: Input must be raw 64-byte Ed25519 signature (R||S). Function internally converts to OpenPGP format for GPG binary. Not compatible with OpenPGP-wrapped signatures (use gpg_verify_signature_with_binary()).
Key trust checking: GPG binary checks key trust and expiry. Verification fails if key is expired, revoked, or untrusted.
Public key requirement: Key must be in GPG keyring for verification. Import public key first with gpg --import <public_key_file>.
Return value interpretation:
  • 0: Signature is cryptographically valid and key is trusted
  • -1: Signature invalid, key not found, key untrusted, or other error
Error conditions: Returns -1 if:
  • Signature cryptographically invalid
  • Key ID not found in keyring
  • Key is expired or revoked
  • Key is not trusted (not in web of trust)
  • gpg binary not found in PATH
  • OpenPGP conversion fails
Warning
GPG binary required: Requires gpg binary in PATH. Returns -1 if GPG is not installed or not accessible.
Ed25519 only: Only Ed25519 signatures are supported (OpenPGP algorithm 22). RSA/ECDSA signatures will return error.
Key must be imported: Public key must exist in GPG keyring. Returns -1 if key is not found (import with gpg --import).
Trust required: GPG checks key trust status. Verification may fail if key is not in web of trust.

Definition at line 37 of file verification.c.

39 {
40 // Note: We don't use the raw signature parameter directly.
41 // Instead, we regenerate the OpenPGP signature using GPG (Ed25519 is
42 // deterministic).
43 (void)signature;
44
45 log_debug("Verifying signature with key ID %s using gpg --verify", key_id);
46
47 // To verify with GPG, we need to:
48 // 1. Reconstruct the OpenPGP signature packet from the raw R||S signature
49 // 2. Write message and signature to temp files
50 // 3. Call gpg --verify
51
52 // First, reconstruct OpenPGP signature by signing the same message
53 // Since Ed25519 is deterministic, we should get the same OpenPGP packet
54 uint8_t openpgp_signature[GPG_SIGNATURE_PACKET_CAPACITY];
55 size_t openpgp_len = 0;
56
57 int sign_result = gpg_sign_with_key(key_id, message, message_len,
58 openpgp_signature, &openpgp_len);
59 if (sign_result != 0) {
60 log_error("Failed to create reference signature for verification");
61 return -1;
62 }
63
64 // Now verify using gpg --verify
65 char msg_path[PLATFORM_MAX_PATH_LENGTH];
66 char sig_path[PLATFORM_MAX_PATH_LENGTH];
67 int msg_fd = -1;
68 int sig_fd = -1;
69
70 if (platform_create_temp_file(msg_path, sizeof(msg_path), "gpg_verify_msg",
71 &msg_fd) != 0) {
72 log_error("Failed to create temporary message file");
73 return -1;
74 }
75
76 if (platform_create_temp_file(sig_path, sizeof(sig_path), "gpg_verify_sig",
77 &sig_fd) != 0) {
78 platform_delete_temp_file(msg_path);
79 log_error("Failed to create temporary signature file");
80 return -1;
81 }
82
83 // Write message
84 if (write(msg_fd, message, (unsigned int)message_len) !=
85 (ssize_t)message_len) {
86 log_error("Failed to write message to temp file");
87 close(msg_fd);
88 close(sig_fd);
89 platform_delete_temp_file(msg_path);
90 platform_delete_temp_file(sig_path);
91 return -1;
92 }
93 close(msg_fd);
94
95 // Write OpenPGP signature
96 if (write(sig_fd, openpgp_signature, (unsigned int)openpgp_len) !=
97 (ssize_t)openpgp_len) {
98 log_error("Failed to write signature to temp file");
99 close(sig_fd);
100 platform_delete_temp_file(msg_path);
101 platform_delete_temp_file(sig_path);
102 return -1;
103 }
104 close(sig_fd);
105
106 // Call gpg --verify
108 safe_snprintf(cmd, sizeof(cmd), "gpg --verify '%s' '%s' 2>&1", sig_path,
109 msg_path);
110 log_debug("Running: %s", cmd);
111
112 FILE *fp;
113 platform_popen("gpg_verify", cmd, "r", &fp);
114 if (!fp) {
115 log_error("Failed to run gpg --verify");
116 platform_unlink(msg_path);
117 platform_unlink(sig_path);
118 return -1;
119 }
120
122 size_t output_len = fread(output, 1, sizeof(output) - 1, fp);
123 int exit_code = platform_pclose(&fp);
124
125 // Cleanup temp files
126 platform_delete_temp_file(msg_path);
127 platform_delete_temp_file(sig_path);
128
129 if (exit_code == 0) {
130 log_debug("GPG signature verification PASSED");
131 return 0;
132 } else {
133 log_error("GPG signature verification FAILED (exit code %d)", exit_code);
134 if (output_len > 0) {
135 log_debug("GPG output: %s", output);
136 }
137 return -1;
138 }
139}
#define CRYPTO_GPG_VERIFICATION_OUTPUT_BUFFER_SIZE
Definition verification.c:9
#define CRYPTO_GPG_VERIFICATION_CMD_BUFFER_SIZE
Definition verification.c:8

References CRYPTO_GPG_VERIFICATION_CMD_BUFFER_SIZE, CRYPTO_GPG_VERIFICATION_OUTPUT_BUFFER_SIZE, ED25519_SIGNATURE_SIZE, gpg_sign_with_key(), GPG_SIGNATURE_PACKET_CAPACITY, log_debug, log_error, platform_pclose(), and platform_popen().

Referenced by ed25519_verify_signature().

◆ gpg_verify_signature()

int gpg_verify_signature ( const uint8_t * public_key,
const uint8_t * message,
size_t message_len,
const uint8_t * signature )

#include <include/ascii-chat/crypto/gpg/verification.h>

Verify Ed25519 signature using libgcrypt (no GPG binary required).

Parameters
public_key32-byte Ed25519 public key (must not be NULL)
messageMessage that was signed (must not be NULL)
message_lenMessage length in bytes (must be > 0)
signature64-byte Ed25519 signature (must not be NULL)
Returns
0 on success (valid signature), -1 on error (invalid signature or error)

Verifies Ed25519 signature directly using libgcrypt cryptographic library. Does not require GPG binary - performs pure cryptographic verification.

Note
Verification method: Uses libgcrypt's gcry_pk_verify() for Ed25519. Pure cryptographic verification - no key trust or expiry checking.
No GPG required: Works without GPG binary installed. Only requires libgcrypt library (linked during build).
Public key format: Accepts raw 32-byte Ed25519 public key. Can be extracted from GPG keyring using gpg_get_public_key().
Signature format: Input must be raw 64-byte Ed25519 signature (R||S). Compatible with signatures from gpg_sign_detached_ed25519(). Not compatible with OpenPGP-wrapped signatures.
No trust checking: Only verifies cryptographic signature validity. Does not check key expiry, revocation, or trust status. Use gpg_verify_detached_ed25519() if trust checking is needed.
Performance: Faster than GPG binary verification (no subprocess spawning). Suitable for high-frequency verification operations.
Use case: Prefer this when:
  • You have raw public key (not just key ID)
  • You don't need key trust/expiry checking
  • You want faster verification (no subprocess)
  • GPG binary may not be installed
Return value interpretation:
  • 0: Signature is cryptographically valid for given public key
  • -1: Signature invalid or verification error
Buffer requirements:
  • public_key: Must be exactly 32 bytes (Ed25519 public key)
  • signature: Must be exactly 64 bytes (Ed25519 signature)
Error conditions: Returns -1 if:
  • Signature cryptographically invalid
  • libgcrypt initialization fails
  • Public key format invalid
  • Signature format invalid
Warning
Ed25519 only: Only Ed25519 signatures are supported. Other key types will cause libgcrypt errors.
No trust checking: Does not verify key trust, expiry, or revocation. Only checks cryptographic signature validity.
Buffer sizes: public_key must be 32 bytes, signature must be 64 bytes. Other sizes will cause verification to fail.

Definition at line 141 of file verification.c.

142 {
143#ifdef HAVE_LIBGCRYPT
144 gcry_error_t err;
145 gcry_sexp_t s_pubkey = NULL;
146 gcry_sexp_t s_sig = NULL;
147 gcry_sexp_t s_data = NULL;
148
149 // Initialize libgcrypt if not already done
150 if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) {
151 gcry_check_version(NULL);
152 gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
153 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
154 }
155
156 // Build public key S-expression: (public-key (ecc (curve Ed25519) (flags
157 // eddsa) (q %b))) Must include (flags eddsa) to match libgcrypt's Ed25519
158 // test suite. See libgcrypt/tests/t-ed25519.c line 246-251.
159 err =
160 gcry_sexp_build(&s_pubkey, NULL,
161 "(public-key (ecc (curve Ed25519) (flags eddsa) (q %b)))",
162 32, public_key);
163 if (err) {
164 log_error("Failed to build public key S-expression: %s",
165 gcry_strerror(err));
166 return -1;
167 }
168
169 // Build signature S-expression: (sig-val (eddsa (r %b) (s %b)))
170 // Signature is 64 bytes: first 32 bytes are R, last 32 bytes are S
171 err = gcry_sexp_build(&s_sig, NULL, "(sig-val (eddsa (r %b) (s %b)))", 32,
172 signature, 32, signature + 32);
173 if (err) {
174 log_error("Failed to build signature S-expression: %s", gcry_strerror(err));
175 gcry_sexp_release(s_pubkey);
176 return -1;
177 }
178
179 // Build data S-expression with raw message
180 // According to libgcrypt's test suite (t-ed25519.c line 273),
181 // Ed25519 data should be: (data (value %b)) with no flags.
182 // The (flags eddsa) belongs in the key S-expression above, not in the data.
183 // GPG agent's internal format is different - this is the correct libgcrypt
184 // API usage.
185 err =
186 gcry_sexp_build(&s_data, NULL, "(data (value %b))", message_len, message);
187 if (err) {
188 log_error("Failed to build data S-expression: %s", gcry_strerror(err));
189 gcry_sexp_release(s_pubkey);
190 gcry_sexp_release(s_sig);
191 return -1;
192 }
193
194 // Debug logging
195 char pubkey_hex[HEX_STRING_SIZE_32];
196 char r_hex[HEX_STRING_SIZE_32];
197 char s_hex[HEX_STRING_SIZE_32];
199
200 for (int i = 0; i < 32; i++) {
201 safe_snprintf(pubkey_hex + i * 2, 3, "%02x", public_key[i]);
202 safe_snprintf(r_hex + i * 2, 3, "%02x", signature[i]);
203 safe_snprintf(s_hex + i * 2, 3, "%02x", signature[32 + i]);
204 }
205 for (size_t i = 0; i < (message_len < 32 ? message_len : 32); i++) {
206 safe_snprintf(msg_hex + i * 2, 3, "%02x", message[i]);
207 }
208
209 log_debug("pubkey=%s", pubkey_hex);
210 log_debug("R=%s", r_hex);
211 log_debug("S=%s", s_hex);
212 log_debug("msg=%s (len=%zu)", msg_hex, message_len);
213
214 // Verify the signature
215 err = gcry_pk_verify(s_sig, s_data, s_pubkey);
216
217 // Clean up S-expressions
218 gcry_sexp_release(s_pubkey);
219 gcry_sexp_release(s_sig);
220 gcry_sexp_release(s_data);
221
222 if (err) {
223 log_debug("Signature verification failed: %s", gcry_strerror(err));
224 return -1;
225 }
226
227 log_debug("Signature verified successfully");
228 return 0;
229#else
230 // Explicitly mark parameters as unused when libgcrypt is not available
231 (void)public_key;
232 (void)message;
233 (void)message_len;
234 (void)signature;
235 log_error("libgcrypt not available");
236 return -1;
237#endif
238}
#define CRYPTO_GPG_VERIFICATION_MSG_HEX_BUFFER_SIZE

References CRYPTO_GPG_VERIFICATION_MSG_HEX_BUFFER_SIZE, HEX_STRING_SIZE_32, log_debug, and log_error.

◆ gpg_verify_signature_with_binary()

int gpg_verify_signature_with_binary ( const uint8_t * signature,
size_t signature_len,
const uint8_t * message,
size_t message_len,
const char * expected_key_id )

#include <include/ascii-chat/crypto/gpg/verification.h>

Verify OpenPGP signature using GPG binary.

Parameters
signatureGPG signature in OpenPGP packet format (must not be NULL)
signature_lenSignature length in bytes (must be > 0)
messageMessage that was signed (must not be NULL)
message_lenMessage length in bytes (must be > 0)
expected_key_idExpected GPG key ID for signature (optional, can be NULL)
Returns
0 on success (valid signature), -1 on error (invalid signature or error)

Verifies OpenPGP-formatted signature using gpg --verify command. Accepts full OpenPGP signature packets from gpg_sign_with_key().

Note
Verification method: Uses gpg --verify on OpenPGP signature packet. Checks both cryptographic validity and key trust status.
Signature format: Input must be OpenPGP signature packet (binary format). Compatible with output from gpg_sign_with_key(). Not compatible with raw 64-byte Ed25519 signatures (use gpg_verify_detached_ed25519()).
OpenPGP parsing: GPG binary parses signature packet to extract:
  • Signature algorithm (must be Ed25519/algorithm 22)
  • Signing key ID
  • Signature data
Key ID checking: If expected_key_id is provided, verifies signature was made by that key. Returns -1 if signature is from different key (prevents key substitution attacks).
Optional key verification: If expected_key_id is NULL, accepts signature from any key. Useful when you don't know signer's key ID in advance.
Public key requirement: Signing key must be in GPG keyring for verification. Import public key first with gpg --import <public_key_file>.
Key trust checking: GPG binary checks key trust and expiry. Verification fails if key is expired, revoked, or untrusted.
Variable length: OpenPGP signatures are variable length (typically 150-200 bytes). Must pass actual signature length in signature_len parameter.
Use case: Prefer this when:
  • You have OpenPGP-formatted signature (from gpg_sign_with_key())
  • You need key trust/expiry checking
  • You want to verify signer identity (via expected_key_id)
Return value interpretation:
  • 0: Signature valid, from expected key (if specified), and key trusted
  • -1: Signature invalid, wrong key, key untrusted, or other error
Error conditions: Returns -1 if:
  • Signature cryptographically invalid
  • Signature from unexpected key (if expected_key_id specified)
  • Signing key not found in keyring
  • Key is expired or revoked
  • Key is not trusted
  • gpg binary not found in PATH
  • OpenPGP packet parsing fails
Warning
GPG binary required: Requires gpg binary in PATH. Returns -1 if GPG is not installed or not accessible.
Ed25519 only: Only Ed25519 signatures are supported (OpenPGP algorithm 22). RSA/ECDSA signatures will return error.
Key must be imported: Signing public key must exist in GPG keyring. Returns -1 if key is not found (import with gpg --import).
Trust required: GPG checks key trust status. Verification may fail if key is not in web of trust.
Key ID mismatch: If expected_key_id is provided and signature is from different key, verification fails even if signature is cryptographically valid.

Definition at line 240 of file verification.c.

243 {
244 // Validate inputs
245 if (!signature || signature_len == 0 || signature_len > 512) {
246 log_error("Invalid signature (expected 1-512 bytes, got %zu)",
247 signature_len);
248 return -1;
249 }
250 if (!message || message_len == 0) {
251 log_error("Invalid message");
252 return -1;
253 }
254
255 // Create temporary files for signature and message
256 char sig_path[PLATFORM_MAX_PATH_LENGTH];
257 char msg_path[PLATFORM_MAX_PATH_LENGTH];
258 int sig_fd = -1;
259 int msg_fd = -1;
260 int result = -1;
261
262 // Create temp files using platform abstraction
263 if (platform_create_temp_file(sig_path, sizeof(sig_path), "asciichat_sig",
264 &sig_fd) != 0) {
265 log_error("Failed to create signature temp file");
266 return -1;
267 }
268
269 if (platform_create_temp_file(msg_path, sizeof(msg_path), "asciichat_msg",
270 &msg_fd) != 0) {
271 log_error("Failed to create message temp file");
272 platform_delete_temp_file(sig_path);
273 return -1;
274 }
275
276#ifdef _WIN32
277 // Windows: Write to already-created files using CreateFileA
278 HANDLE sig_handle =
279 CreateFileA(sig_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
280 FILE_ATTRIBUTE_TEMPORARY, NULL);
281 if (sig_handle == INVALID_HANDLE_VALUE) {
282 log_error("Failed to open signature temp file: %lu", GetLastError());
283 platform_delete_temp_file(sig_path);
284 platform_delete_temp_file(msg_path);
285 return -1;
286 }
287
288 DWORD bytes_written;
289 if (!WriteFile(sig_handle, signature, (DWORD)signature_len, &bytes_written,
290 NULL) ||
291 bytes_written != signature_len) {
292 log_error("Failed to write signature to temp file: %lu", GetLastError());
293 CloseHandle(sig_handle);
294 platform_delete_temp_file(sig_path);
295 platform_delete_temp_file(msg_path);
296 return -1;
297 }
298 CloseHandle(sig_handle);
299
300 HANDLE msg_handle =
301 CreateFileA(msg_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
302 FILE_ATTRIBUTE_TEMPORARY, NULL);
303 if (msg_handle == INVALID_HANDLE_VALUE) {
304 log_error("Failed to open message temp file: %lu", GetLastError());
305 platform_delete_temp_file(sig_path);
306 platform_delete_temp_file(msg_path);
307 return -1;
308 }
309
310 if (!WriteFile(msg_handle, message, (DWORD)message_len, &bytes_written,
311 NULL) ||
312 bytes_written != message_len) {
313 log_error("Failed to write message to temp file: %lu", GetLastError());
314 CloseHandle(msg_handle);
315 platform_delete_temp_file(sig_path);
316 platform_delete_temp_file(msg_path);
317 return -1;
318 }
319 CloseHandle(msg_handle);
320
321#else
322 // Unix: Write to open file descriptors returned by platform_create_temp_file
323 ssize_t sig_written = write(sig_fd, signature, signature_len);
324 if (sig_written != (ssize_t)signature_len) {
325 log_error("Failed to write signature to temp file: %s",
326 SAFE_STRERROR(errno));
327 close(sig_fd);
328 close(msg_fd);
329 platform_delete_temp_file(sig_path);
330 platform_delete_temp_file(msg_path);
331 return -1;
332 }
333 close(sig_fd);
334
335 ssize_t msg_written = write(msg_fd, message, message_len);
336 if (msg_written != (ssize_t)message_len) {
337 log_error("Failed to write message to temp file: %s", SAFE_STRERROR(errno));
338 close(msg_fd);
339 platform_delete_temp_file(sig_path);
340 platform_delete_temp_file(msg_path);
341 return -1;
342 }
343 close(msg_fd);
344#endif
345
346 // Build gpg --verify command
347 char cmd[BUFFER_SIZE_LARGE];
348#ifdef _WIN32
349 safe_snprintf(cmd, sizeof(cmd), "gpg --verify \"%s\" \"%s\" 2>&1", sig_path,
350 msg_path);
351#else
352 safe_snprintf(cmd, sizeof(cmd), "gpg --verify '%s' '%s' 2>&1", sig_path,
353 msg_path);
354#endif
355
356 log_debug("Running GPG verify command: %s", cmd);
357
358 // Execute gpg --verify command
359 FILE *fp;
360 platform_popen("gpg_verify", cmd, "r", &fp);
361 if (!fp) {
362 log_error("Failed to execute gpg --verify command");
363 goto cleanup;
364 }
365
366 // Parse output for "Good signature" and verify key ID
367 char line[BUFFER_SIZE_MEDIUM];
368 bool found_good_sig = false;
369 bool found_key_id = false;
370
371 while (fgets(line, sizeof(line), fp)) {
372 log_debug("GPG output: %s", line);
373
374 // Check for "Good signature"
375 if (strstr(line, "Good signature")) {
376 found_good_sig = true;
377 }
378
379 // Check if this line contains the expected key ID (GPG outputs key ID on
380 // separate line)
381 if (expected_key_id && strlen(expected_key_id) > 0) {
382 if (strstr(line, expected_key_id)) {
383 found_key_id = true;
384 log_debug("Found expected key ID in GPG output: %s", expected_key_id);
385 }
386 }
387
388 // Check for signature errors
389 if (strstr(line, "BAD signature")) {
390 log_error("GPG reports BAD signature");
391 platform_pclose(&fp);
392 fp = NULL;
393 goto cleanup;
394 }
395 }
396
397 // Check exit code
398 int status = platform_pclose(&fp);
399 fp = NULL;
400
401#ifdef _WIN32
402 int exit_code = status;
403#else
404 int exit_code = WEXITSTATUS(status);
405#endif
406
407 if (exit_code != 0) {
408 log_error("GPG verify failed with exit code: %d", exit_code);
409 goto cleanup;
410 }
411
412 if (!found_good_sig) {
413 log_error("GPG verify did not report 'Good signature'");
414 goto cleanup;
415 }
416
417 // If expected_key_id was provided, verify we found it in the output
418 if (expected_key_id && strlen(expected_key_id) > 0) {
419 if (!found_key_id) {
420 log_error("GPG signature key ID does not match expected key ID: %s",
421 expected_key_id);
422 goto cleanup;
423 }
424 }
425
426 log_debug("GPG signature verified successfully via gpg --verify binary");
427 result = 0;
428
429cleanup:
430 // Clean up temp files
431 platform_delete_temp_file(sig_path);
432 platform_delete_temp_file(msg_path);
433
434 if (fp) {
435 platform_pclose(&fp);
436 }
437
438 return result;
439}

References BUFFER_SIZE_LARGE, BUFFER_SIZE_MEDIUM, bytes_written, log_debug, log_error, platform_pclose(), platform_popen(), and SAFE_STRERROR.

◆ known_hosts_destroy()

void known_hosts_destroy ( void )

#include <include/ascii-chat/crypto/known_hosts.h>

Cleanup function to free cached known_hosts path.

Frees cached known_hosts file path. Should be called at program shutdown to clean up resources.

Note
Path caching: Path is cached after first call to get_known_hosts_path(). This function frees the cached path.
Safe to call multiple times: Function checks if cache exists before freeing. Safe to call even if cache was never allocated.

Definition at line 913 of file known_hosts.c.

913 {
914 if (g_known_hosts_path_cache) {
915 SAFE_FREE(g_known_hosts_path_cache);
916 g_known_hosts_path_cache = NULL;
917 }
918}

References SAFE_FREE.

Referenced by asciichat_shared_destroy().

◆ openpgp_base64_decode()

asciichat_error_t openpgp_base64_decode ( const char * base64,
size_t base64_len,
uint8_t ** binary_out,
size_t * binary_len )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Decode PGP armored base64 data.

Parameters
base64Base64-encoded string
base64_lenLength of base64 string
binary_outOutput buffer for decoded binary data (allocated by function)
binary_lenOutput parameter for decoded data length
Returns
ASCIICHAT_OK on success, error code on failure

Decodes base64 data from PGP armored format:

  • Removes whitespace (newlines, spaces, tabs)
  • Decodes using libsodium's base64 decoder
  • Allocates output buffer (caller must free)
Note
Caller must free *binary_out using SAFE_FREE()

Definition at line 40 of file openpgp.c.

42 {
43 if (!base64 || !binary_out || !binary_len) {
45 "Invalid parameters for base64 decode");
46 }
47
48 // Remove whitespace from base64 input (PGP armor has newlines)
49 SAFE_MALLOC_DEFER_FREE(clean_base64, base64_len + 1, char *);
50 char *clean_ptr = clean_base64;
51 for (size_t i = 0; i < base64_len; i++) {
52 if (base64[i] != '\n' && base64[i] != '\r' && base64[i] != ' ' &&
53 base64[i] != '\t') {
54 *clean_ptr++ = base64[i];
55 }
56 }
57 *clean_ptr = '\0';
58 size_t clean_len = (size_t)(clean_ptr - clean_base64);
59
60 // Allocate max possible output size
61 *binary_out = SAFE_MALLOC(clean_len, uint8_t *);
62
63 const char *end;
64 int result =
65 sodium_base642bin(*binary_out, clean_len, clean_base64, clean_len, NULL,
66 binary_len, &end, sodium_base64_VARIANT_ORIGINAL);
67
68 if (result != 0) {
69 SAFE_FREE(*binary_out);
71 "Failed to decode base64 PGP armored data");
72 }
73
74 return ASCIICHAT_OK;
75}
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
@ ERROR_CRYPTO_KEY

References ASCIICHAT_OK, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, SAFE_FREE, SAFE_MALLOC, SAFE_MALLOC_DEFER_FREE, and SET_ERRNO.

Referenced by openpgp_parse_armored_pubkey(), and openpgp_parse_armored_seckey().

◆ openpgp_extract_ed25519_from_mpi()

asciichat_error_t openpgp_extract_ed25519_from_mpi ( const uint8_t * mpi,
size_t mpi_len,
uint8_t ed25519_pk[32] )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Extract Ed25519 public key from MPI-encoded data.

Parameters
mpiMPI-encoded public key data
mpi_lenLength of MPI data
ed25519_pkOutput buffer for Ed25519 public key (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts Ed25519 public key from OpenPGP MPI (Multi-Precision Integer) format:

  • 2 bytes: bit count (should be ~263 bits for Ed25519 with prefix)
  • 1 byte: 0x40 prefix byte (Ed25519 marker)
  • 32 bytes: Ed25519 public key

RFC 4880 Section 3.2: Multiprecision Integers

References ED25519_PUBLIC_KEY_SIZE.

◆ openpgp_parse_armored_pubkey()

asciichat_error_t openpgp_parse_armored_pubkey ( const char * armored_text,
uint8_t ed25519_pk[32] )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse PGP armored key block and extract Ed25519 public key.

Parameters
armored_textPGP armored text (--—BEGIN PGP PUBLIC KEY BLOCK--—)
ed25519_pkOutput buffer for Ed25519 public key (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Parses a complete PGP armored key block:

  1. Extracts base64 data between BEGIN/END markers
  2. Decodes base64 to binary OpenPGP packets
  3. Parses packet headers to find public key packet (tag 6)
  4. Extracts Ed25519 public key from packet body
Note
Only supports Ed25519 keys (algorithm 22)
Ignores signatures, user IDs, and other packet types
Does not verify checksums or signatures

Example armored format:

-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaWxCORYJKwYBBAHaRw8BAQdAOaykIMyaQi8CBTNiF9o/Nbm6L5DwR9h1maS3
yqG5PFO0MmFzY2lpLWNoYXQgRGlzY292ZXJ5IFNlcnZpY2UgPGFjZHNAYXNjaWkt
...
=+ncm
-----END PGP PUBLIC KEY BLOCK-----

References ED25519_PUBLIC_KEY_SIZE.

◆ openpgp_parse_armored_seckey()

asciichat_error_t openpgp_parse_armored_seckey ( const char * armored_text,
uint8_t ed25519_pk[32],
uint8_t ed25519_sk[32] )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse PGP armored secret key block and extract Ed25519 keypair.

Parameters
armored_textPGP armored text (--—BEGIN PGP PRIVATE KEY BLOCK--—)
ed25519_pkOutput buffer for Ed25519 public key (32 bytes)
ed25519_skOutput buffer for Ed25519 secret key (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Parses a complete PGP armored secret key block:

  1. Extracts base64 data between BEGIN/END markers
  2. Decodes base64 to binary OpenPGP packets
  3. Parses packet headers to find secret key packet (tag 5)
  4. Extracts Ed25519 public and secret keys from packet body
Note
Only supports Ed25519 keys (algorithm 22)
Only supports unencrypted secret keys (S2K usage = 0)
Ignores signatures, user IDs, and other packet types
Does not verify checksums or signatures

Example armored format:

-----BEGIN PGP PRIVATE KEY BLOCK-----
lIYEaWxCORYJKwYBBAHaRw8BAQdAOaykIMyaQi8CBTNiF9o/Nbm6L5DwR9h1maS3
yqG5PFMAAQDm8...
=abcd
-----END PGP PRIVATE KEY BLOCK-----

References ED25519_PUBLIC_KEY_SIZE, and ED25519_SEED_SIZE.

◆ openpgp_parse_binary_pubkey()

asciichat_error_t openpgp_parse_binary_pubkey ( const uint8_t * data,
size_t data_len,
uint8_t ed25519_pk[32] )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse a binary OpenPGP public-key packet stream and extract its Ed25519 key.

References ED25519_PUBLIC_KEY_SIZE.

◆ openpgp_parse_binary_seckey()

asciichat_error_t openpgp_parse_binary_seckey ( const uint8_t * data,
size_t data_len,
uint8_t ed25519_pk[32],
uint8_t ed25519_sk[32] )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse an unencrypted binary OpenPGP secret-key packet stream.

References ED25519_PUBLIC_KEY_SIZE, and ED25519_SEED_SIZE.

◆ openpgp_parse_packet_header()

asciichat_error_t openpgp_parse_packet_header ( const uint8_t * data,
size_t data_len,
openpgp_packet_header_t * header )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse OpenPGP packet header.

Parameters
dataPacket data (starts with packet header byte)
data_lenLength of packet data
headerOutput parameter for parsed header
Returns
ASCIICHAT_OK on success, error code on failure

Parses OpenPGP packet header (old or new format):

  • Old format: bit 7 = 1, bit 6 = 0, bits 5-2 = tag, bits 1-0 = length type
  • New format: bit 7 = 1, bit 6 = 1, bits 5-0 = tag

RFC 4880 Section 4.2: Packet Headers

Definition at line 81 of file openpgp.c.

83 {
84 if (!data || !header || data_len == 0) {
86 "Invalid parameters for packet header parsing");
87 }
88
89 memset(header, 0, sizeof(openpgp_packet_header_t));
90
91 uint8_t ctb = data[0]; // Cipher Type Byte
92
93 // Check if bit 7 is set (all packets must have bit 7 = 1)
94 if ((ctb & 0x80) == 0) {
96 "Invalid OpenPGP packet: bit 7 not set in CTB");
97 }
98
99 // Check if new format (bit 6 = 1) or old format (bit 6 = 0)
100 if (ctb & 0x40) {
101 // New format: bits 5-0 = tag
102 header->new_format = true;
103 header->tag = ctb & 0x3F;
104
105 if (data_len < 2) {
107 "Insufficient data for new format packet header");
108 }
109
110 uint8_t len_byte = data[1];
111
112 if (len_byte < 192) {
113 // One-octet length
114 header->length = len_byte;
115 header->header_len = 2;
116 } else if (len_byte < 224) {
117 // Two-octet length
118 if (data_len < 3) {
120 "Insufficient data for two-octet length");
121 }
122 header->length = ((len_byte - 192) << 8) + data[2] + 192;
123 header->header_len = 3;
124 } else if (len_byte == 255) {
125 // Five-octet length
126 if (data_len < 6) {
128 "Insufficient data for five-octet length");
129 }
130 header->length = ((size_t)data[2] << 24) | ((size_t)data[3] << 16) |
131 ((size_t)data[4] << 8) | data[5];
132 header->header_len = 6;
133 } else {
134 // Partial body length (not supported for our use case)
135 return SET_ERRNO(ERROR_CRYPTO_KEY, "Partial body length not supported");
136 }
137 } else {
138 // Old format: bits 5-2 = tag, bits 1-0 = length type
139 header->new_format = false;
140 header->tag = (ctb >> 2) & 0x0F;
141 uint8_t length_type = ctb & 0x03;
142
143 switch (length_type) {
144 case 0: // One-octet length
145 if (data_len < 2) {
147 "Insufficient data for one-octet length");
148 }
149 header->length = data[1];
150 header->header_len = 2;
151 break;
152
153 case 1: // Two-octet length
154 if (data_len < 3) {
156 "Insufficient data for two-octet length");
157 }
158 header->length = ((size_t)data[1] << 8) | data[2];
159 header->header_len = 3;
160 break;
161
162 case 2: // Four-octet length
163 if (data_len < 5) {
165 "Insufficient data for four-octet length");
166 }
167 header->length = ((size_t)data[1] << 24) | ((size_t)data[2] << 16) |
168 ((size_t)data[3] << 8) | data[4];
169 header->header_len = 5;
170 break;
171
172 case 3: // Indeterminate length (not supported)
173 return SET_ERRNO(ERROR_CRYPTO_KEY, "Indeterminate length not supported");
174
175 default:
176 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid length type: %u",
177 length_type);
178 }
179 }
180
181 log_debug("OpenPGP packet: tag=%u, length=%zu, header_len=%zu, new_format=%d",
182 header->tag, header->length, header->header_len,
183 header->new_format);
184
185 return ASCIICHAT_OK;
186}
The framing fields needed to locate and classify one OpenPGP packet body.
Definition openpgp.h:81

References ASCIICHAT_OK, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, log_debug, and SET_ERRNO.

Referenced by openpgp_parse_armored_seckey(), openpgp_parse_binary_pubkey(), and openpgp_parse_binary_seckey().

◆ openpgp_parse_public_key_packet()

asciichat_error_t openpgp_parse_public_key_packet ( const uint8_t * packet_body,
size_t body_len,
openpgp_public_key_t * pubkey )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse OpenPGP Public Key Packet (tag 6).

Parameters
packet_bodyPacket body data (after header)
body_lenLength of packet body
pubkeyOutput parameter for parsed public key
Returns
ASCIICHAT_OK on success, error code on failure

Parses Public Key Packet (tag 6) body:

  • Version (1 byte, must be 4)
  • Creation time (4 bytes, Unix timestamp)
  • Algorithm (1 byte, 22 = EdDSA)
  • Public key material (MPI format for Ed25519)

RFC 4880 Section 5.5.2: Public-Key Packet Formats

Note
Only supports version 4 packets
Only supports EdDSA (algorithm 22)

Definition at line 234 of file openpgp.c.

235 {
236 if (!packet_body || !pubkey || body_len < 6) {
238 "Invalid parameters for public key packet parsing");
239 }
240
241 memset(pubkey, 0, sizeof(openpgp_public_key_t));
242
243 size_t offset = 0;
244
245 // Version (1 byte, must be 4)
246 pubkey->version = packet_body[offset++];
247 if (pubkey->version != 4) {
248 return SET_ERRNO(
250 "Unsupported OpenPGP public key version: %u (only version 4 supported)",
251 pubkey->version);
252 }
253
254 // Creation time (4 bytes, big-endian Unix timestamp)
255 pubkey->created = ((uint32_t)packet_body[offset] << 24) |
256 ((uint32_t)packet_body[offset + 1] << 16) |
257 ((uint32_t)packet_body[offset + 2] << 8) |
258 packet_body[offset + 3];
259 offset += 4;
260
261 // Algorithm (1 byte)
262 pubkey->algorithm = packet_body[offset++];
263
264 log_debug("Public key packet: version=%u, created=%u, algorithm=%u",
265 pubkey->version, pubkey->created, pubkey->algorithm);
266
267 // Only support EdDSA (algorithm 22)
268 if (pubkey->algorithm != OPENPGP_ALGO_EDDSA) {
269 return SET_ERRNO(
271 "Unsupported public key algorithm: %u (only EdDSA/22 supported)",
272 pubkey->algorithm);
273 }
274
275 // EdDSA (Ed25519) keys have a special encoding:
276 // - OID for the curve (variable length)
277 // - 0x40 prefix byte
278 // - 32 bytes of Ed25519 public key
279 //
280 // We search for the 0x40 prefix and extract the following 32 bytes
281
282 // Search for 0x40 prefix byte in the remaining packet data
283 bool found_prefix = false;
284 size_t key_offset = 0;
285
286 for (size_t i = offset; i < body_len - 32; i++) {
287 if (packet_body[i] == 0x40) {
288 key_offset = i + 1; // Point to first byte after 0x40
289 found_prefix = true;
290 log_debug("Found Ed25519 key prefix 0x40 at offset %zu", i);
291 break;
292 }
293 }
294
295 if (!found_prefix) {
297 "Ed25519 public key prefix (0x40) not found in packet");
298 }
299
300 if (key_offset + 32 > body_len) {
301 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for Ed25519 public "
302 "key (need 32 bytes after 0x40 prefix)");
303 }
304
305 // Extract the 32-byte Ed25519 public key
306 memcpy(pubkey->pubkey, packet_body + key_offset, ED25519_PUBLIC_KEY_SIZE);
307
308 // Calculate Key ID (last 8 bytes of SHA-1 fingerprint)
309 // For now, we'll skip fingerprint calculation and just extract from packet if
310 // available The keyid is typically at a fixed offset for Ed25519 keys We'll
311 // compute it properly by hashing the public key material
312
313 // For version 4 keys, fingerprint = SHA-1(0x99 || length || packet_body)
314 // Key ID = last 8 bytes of fingerprint
315 // For simplicity, we'll set keyid to 0 for now (not critical for our use
316 // case)
317 pubkey->keyid = 0;
318
319 return ASCIICHAT_OK;
320}
#define OPENPGP_ALGO_EDDSA
OpenPGP algorithm ID for EdDSA (Ed25519).
Definition openpgp.h:61
The parsed identity portion of an OpenPGP public-key packet.
Definition openpgp.h:104
uint64_t keyid
OpenPGP Key ID (last 8 bytes of fingerprint).
Definition openpgp.h:109
uint32_t created
Creation timestamp (Unix epoch).
Definition openpgp.h:106
uint8_t pubkey[32]
Ed25519 public key (32 bytes).
Definition openpgp.h:108
uint8_t algorithm
Public key algorithm (22 = EdDSA).
Definition openpgp.h:107
uint8_t version
Packet version (should be 4).
Definition openpgp.h:105

References openpgp_public_key_t::algorithm, ASCIICHAT_OK, openpgp_public_key_t::created, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, openpgp_public_key_t::keyid, log_debug, OPENPGP_ALGO_EDDSA, openpgp_public_key_t::pubkey, SET_ERRNO, and openpgp_public_key_t::version.

Referenced by openpgp_parse_binary_pubkey().

◆ openpgp_parse_secret_key_packet()

asciichat_error_t openpgp_parse_secret_key_packet ( const uint8_t * packet_body,
size_t body_len,
openpgp_secret_key_t * seckey )

#include <include/ascii-chat/crypto/gpg/openpgp.h>

Parse OpenPGP Secret Key Packet (tag 5).

Parameters
packet_bodyPacket body data (after header)
body_lenLength of packet body
seckeyOutput parameter for parsed secret key
Returns
ASCIICHAT_OK on success, error code on failure

Parses Secret Key Packet (tag 5) body:

  • Version (1 byte, must be 4)
  • Creation time (4 bytes, Unix timestamp)
  • Algorithm (1 byte, 22 = EdDSA)
  • Public key material (MPI format for Ed25519)
  • S2K usage (1 byte, must be 0 for unencrypted)
  • Secret key material (32 bytes for Ed25519)

RFC 4880 Section 5.5.3: Secret-Key Packet Formats

Note
Only supports version 4 packets
Only supports EdDSA (algorithm 22)
Only supports unencrypted secret keys (S2K usage = 0)

Definition at line 435 of file openpgp.c.

436 {
437 if (!packet_body || !seckey || body_len < 6) {
439 "Invalid parameters for secret key packet parsing");
440 }
441
442 memset(seckey, 0, sizeof(openpgp_secret_key_t));
443
444 size_t offset = 0;
445
446 // Parse public key portion (same as public key packet)
447 // Version (1 byte, must be 4)
448 seckey->version = packet_body[offset++];
449 if (seckey->version != 4) {
450 return SET_ERRNO(
452 "Unsupported OpenPGP secret key version: %u (only version 4 supported)",
453 seckey->version);
454 }
455
456 // Creation time (4 bytes, big-endian Unix timestamp)
457 seckey->created = ((uint32_t)packet_body[offset] << 24) |
458 ((uint32_t)packet_body[offset + 1] << 16) |
459 ((uint32_t)packet_body[offset + 2] << 8) |
460 packet_body[offset + 3];
461 offset += 4;
462
463 // Algorithm (1 byte)
464 seckey->algorithm = packet_body[offset++];
465
466 log_debug("Secret key packet: version=%u, created=%u, algorithm=%u",
467 seckey->version, seckey->created, seckey->algorithm);
468
469 // Only support EdDSA (algorithm 22)
470 if (seckey->algorithm != OPENPGP_ALGO_EDDSA) {
471 return SET_ERRNO(
473 "Unsupported secret key algorithm: %u (only EdDSA/22 supported)",
474 seckey->algorithm);
475 }
476
477 // EdDSA public key: OID + 0x40 prefix + 32 bytes of Ed25519 public key
478 // Search for 0x40 prefix byte
479 bool found_prefix = false;
480 size_t pubkey_offset = 0;
481
482 for (size_t i = offset; i < body_len - 32; i++) {
483 if (packet_body[i] == 0x40) {
484 pubkey_offset = i + 1;
485 found_prefix = true;
486 log_debug("Found Ed25519 public key prefix 0x40 at offset %zu", i);
487 break;
488 }
489 }
490
491 if (!found_prefix) {
492 return SET_ERRNO(
494 "Ed25519 public key prefix (0x40) not found in secret key packet");
495 }
496
497 if (pubkey_offset + 32 > body_len) {
498 return SET_ERRNO(ERROR_CRYPTO_KEY, "Insufficient data for Ed25519 public "
499 "key (need 32 bytes after 0x40 prefix)");
500 }
501
502 // Extract the 32-byte Ed25519 public key
503 memcpy(seckey->pubkey, packet_body + pubkey_offset, ED25519_PUBLIC_KEY_SIZE);
504
505 // Move offset past public key material
506 offset = pubkey_offset + 32;
507
508 // S2K usage byte (1 byte)
509 // 0x00 = secret key is not encrypted
510 // 0xFE or 0xFF = secret key is encrypted with S2K
511 if (offset >= body_len) {
513 "Missing S2K usage byte in secret key packet");
514 }
515
516 uint8_t s2k_usage = packet_body[offset++];
517 log_debug("S2K usage byte: 0x%02x", s2k_usage);
518
519 if (s2k_usage != 0x00) {
520 seckey->is_encrypted = true;
521 log_debug("Detected encrypted secret key (S2K usage = 0x%02x)", s2k_usage);
522 // Don't parse encrypted key material here - caller will need to decrypt
523 // with gpg
524 return ASCIICHAT_OK;
525 }
526
527 seckey->is_encrypted = false;
528
529 // The Ed25519 secret scalar is encoded as an OpenPGP MPI (bit count followed
530 // by bytes).
531 if (offset + 2 > body_len) {
532 return SET_ERRNO(ERROR_CRYPTO_KEY, "Missing Ed25519 secret-key MPI length");
533 }
534 uint16_t secret_bits = (uint16_t)(((uint16_t)packet_body[offset] << 8) |
535 packet_body[offset + 1]);
536 size_t secret_bytes = (secret_bits + 7u) / 8u;
537 offset += 2;
538 if (secret_bits == 0 || secret_bits > 256 ||
539 secret_bytes > sizeof(seckey->seckey) ||
540 offset + secret_bytes + 2 > body_len) {
542 "Invalid Ed25519 secret-key MPI length: %u bits",
543 secret_bits);
544 }
545
546 // Ed25519 private material is 32 bytes; left-pad shorter MPIs as specified by
547 // OpenPGP.
548 memcpy(seckey->seckey + sizeof(seckey->seckey) - secret_bytes,
549 packet_body + offset, secret_bytes);
550
551 log_debug("Extracted Ed25519 secret key");
552
553 return ASCIICHAT_OK;
554}
The parsed public and private material from an OpenPGP secret-key packet.
Definition openpgp.h:128
uint8_t seckey[32]
Ed25519 secret key (32 bytes).
Definition openpgp.h:133
uint8_t pubkey[32]
Ed25519 public key (32 bytes).
Definition openpgp.h:132
bool is_encrypted
True if secret key material is encrypted.
Definition openpgp.h:135
uint32_t created
Creation timestamp (Unix epoch).
Definition openpgp.h:130
uint8_t algorithm
Public key algorithm (22 = EdDSA).
Definition openpgp.h:131
uint8_t version
Packet version (should be 4).
Definition openpgp.h:129

References openpgp_secret_key_t::algorithm, ASCIICHAT_OK, openpgp_secret_key_t::created, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, openpgp_secret_key_t::is_encrypted, log_debug, OPENPGP_ALGO_EDDSA, openpgp_secret_key_t::pubkey, openpgp_secret_key_t::seckey, SET_ERRNO, and openpgp_secret_key_t::version.

Referenced by openpgp_parse_armored_seckey(), and openpgp_parse_binary_seckey().

◆ prompt_unknown_host()

bool prompt_unknown_host ( const char * server_ip,
uint16_t port,
const uint8_t server_key[32] )

#include <include/ascii-chat/crypto/known_hosts.h>

Interactive prompt for unknown host - returns true if user wants to add, false to abort.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
server_keyServer's Ed25519 public key (32 bytes, must not be NULL)
Returns
true if user wants to add to known_hosts, false to abort

Prompts user to add unknown host to known_hosts. Displays server information and key fingerprint for user verification.

Note
Prompt display: Shows server IP:port and key fingerprint (SHA256). Prompts user to accept (add to known_hosts) or reject (abort connection).
Key fingerprint: Displays SHA256 fingerprint of server key for verification. Fingerprint is displayed in hex format (64 hex chars).
Non-interactive mode: If not connected to TTY (snapshot mode), automatically adds host to known_hosts (returns true). This allows automated connections.
Security: User should verify key fingerprint before accepting. Only add host if key fingerprint matches expected value.
Warning
Always check return value. If false, connection should be aborted.

References ED25519_PUBLIC_KEY_SIZE.

◆ prompt_unknown_host_no_identity()

bool prompt_unknown_host_no_identity ( const char * server_ip,
uint16_t port )

#include <include/ascii-chat/crypto/known_hosts.h>

Interactive prompt for unknown host without identity key - returns true if user wants to continue, false to abort.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
Returns
true if user wants to continue (accepts no-identity connection), false to abort

Prompts user to accept unknown host without identity key. Displays server information and warns that identity cannot be verified.

Note
Prompt display: Shows server IP:port and warning that identity cannot be verified. Prompts user to accept (continue connection) or reject (abort connection).
Security warning: Warns that server identity cannot be verified (no identity key). Connection is vulnerable to MITM attacks without identity verification.
Non-interactive mode: If not connected to TTY (snapshot mode), automatically accepts connection (returns true). This allows automated connections.
No-identity entries: If user accepts, adds "no-identity" entry to known_hosts. This tracks that user previously accepted this server without identity verification.
Warning
Security limitation: Cannot verify server identity (no keys to compare). Connection is vulnerable to MITM attacks.
Always check return value. If false, connection should be aborted.

Definition at line 849 of file known_hosts.c.

849 {
850 // Format IP:port with proper bracket notation for IPv6
851 char ip_with_port[BUFFER_SIZE_MEDIUM];
852 if (format_ip_with_port(server_ip, port, ip_with_port,
853 sizeof(ip_with_port)) != ASCIICHAT_OK) {
854 // Fallback to basic format if error
855 safe_snprintf(ip_with_port, sizeof(ip_with_port), "%s:%u", server_ip, port);
856 }
857
858 // LOCALHOST OPTIMIZATION: Skip authentication prompt for localhost addresses
859 // Localhost is inherently trusted (same machine, no network exposure)
860 // This matches SSH behavior (ssh-keyscan doesn't prompt for localhost)
861 if (is_localhost_address(server_ip)) {
862 log_debug("SECURITY: Localhost address %s detected - skipping unknown host "
863 "prompt (localhost is inherently trusted)",
864 ip_with_port);
865 return true; // Silently trust localhost
866 }
867
868 // Check if running in automated/non-interactive environment
869 // In debug builds, Claude Code automation can't interact with prompts
870 if (is_automated_mode()) {
871 SET_ERRNO(ERROR_CRYPTO, "SECURITY: Cannot verify server without identity "
872 "key in non-interactive/automated mode");
873 NOTICE(
874 DANGER, "SERVER IDENTITY MISSING",
875 "ERROR: Cannot verify server without identity key in "
876 "non-interactive/automated mode.\n"
877 "ERROR: This connection is vulnerable to man-in-the-middle attacks!\n"
878 "\n"
879 "To connect to this host:\n"
880 " 1. Run the client interactively (from a terminal with TTY)\n"
881 " 2. Verify you trust this server despite no identity key\n"
882 " 3. Accept the risk when prompted\n"
883 " OR better: Ask server admin to use --key for proper authentication\n"
884 "\n"
885 "Connection aborted for security.\n"
886 "\n");
887 return false;
888 }
889
891 safe_snprintf(question, sizeof(question),
892 "Host '%s' has no identity key.\n"
893 "This connection is vulnerable to man-in-the-middle attacks.\n"
894 "Anyone intercepting it could read your data.\n\n"
895 "Use --key on the server and --server-key on the client to "
896 "verify identity.\n\n"
897 "Are you sure you want to continue connecting",
898 ip_with_port);
899 if (ui_notice_confirm_kind(UI_PROMPT_UNVERIFIED_HOST, UI_NOTICE_DANGER,
900 question, 120)) {
901 NOTICE(DANGER, "UNVERIFIED CONNECTION",
902 "Warning: Proceeding with unverified connection.\n"
903 "Your data may be intercepted by attackers!\n"
904 "\n");
905 return true;
906 }
907
908 log_plain("Connection aborted by user.");
909 return false;
910}
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:635
#define CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE
Definition known_hosts.c:10
bool ui_notice_confirm_kind(ui_prompt_kind_t kind, ui_notice_severity_t severity, const char *text, unsigned timeout_seconds)
Definition notice.c:548
@ UI_NOTICE_DANGER
Definition notice.h:16

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, CRYPTO_KNOWN_HOSTS_QUESTION_BUFFER_SIZE, ERROR_CRYPTO, format_ip_with_port(), log_debug, log_plain, NOTICE, SET_ERRNO, ui_notice_confirm_kind(), and UI_NOTICE_DANGER.

Referenced by crypto_handshake_client_key_exchange().

◆ read_trust_anchors_from_memory()

size_t read_trust_anchors_from_memory ( anchor_list * dst,
const unsigned char * pem_data,
size_t pem_len )

#include <include/ascii-chat/crypto/pem.h>

Read trust anchors from PEM-encoded data in memory.

Parameters
dstPointer to anchor_list to append trust anchors to (must not be NULL)
pem_dataPointer to PEM-encoded certificate data (must not be NULL)
pem_lenLength of PEM data in bytes (must be > 0)
Returns
Number of trust anchors successfully decoded and added, or 0 on error

Parses PEM-encoded CA certificates from a memory buffer and converts them to BearSSL trust anchors. The trust anchors are appended to the provided anchor_list.

Note
PEM format: Accepts PEM-encoded certificates (--—BEGIN CERTIFICATE--—). Supports multiple certificates in single PEM data (concatenated).
Trust anchor parsing: Parses each certificate in PEM data and creates trust anchor structure. Appends trust anchors to anchor_list.
Memory allocation: Dynamically allocates memory for trust anchors. Resizes anchor_list.buf as needed (realloc).
Error handling: Returns 0 on error (parse error, memory error, etc.). Partially parsed trust anchors are retained (not rolled back).
Warning
Memory management: Trust anchors contain dynamically allocated memory. Must call free_ta_contents() for each anchor and free anchor_list.buf.
PEM data format: PEM data must be valid PEM-encoded certificates. Invalid PEM data may cause parse errors or crashes.

Definition at line 469 of file pem.c.

471 {
472 br_x509_certificate *xcs;
473 anchor_list tas = VEC_INIT;
474 size_t u, num;
475
476 xcs = read_certificates_from_memory(pem_data, pem_len, &num);
477 if (xcs == NULL) {
478 return 0;
479 }
480
481 for (u = 0; u < num; u++) {
482 br_x509_trust_anchor ta;
483
484 if (certificate_to_trust_anchor_inner(&ta, &xcs[u]) != ASCIICHAT_OK) {
486 free_certificates(xcs, num);
487 return 0;
488 }
489 VEC_ADD(tas, ta);
490 }
491
492 VEC_ADDMANY(*dst, &VEC_ELT(tas, 0), num);
493 VEC_CLEAR(tas);
494 free_certificates(xcs, num);
495 return num;
496}
void free_ta_contents(br_x509_trust_anchor *ta)
Free the contents of a trust anchor.
Definition pem.c:448
#define VEC_CLEAR(vec)
Definition pem.c:52
#define VEC_CLEAREXT(vec, fun)
Definition pem.c:60
#define VEC_ADDMANY(vec, xp, num)
Definition pem.c:76
#define VEC_ELT(vec, idx)
Definition pem.c:85
#define VEC_INIT
Definition pem.c:49
#define VEC_ADD(vec, x)
Definition pem.c:69
Vector type for trust anchors.
Definition pem.h:87

References ASCIICHAT_OK, free_ta_contents(), VEC_ADD, VEC_ADDMANY, VEC_CLEAR, VEC_CLEAREXT, VEC_ELT, and VEC_INIT.

Referenced by https_get().

◆ remove_known_host()

asciichat_error_t remove_known_host ( const char * server_ip,
uint16_t port )

#include <include/ascii-chat/crypto/known_hosts.h>

Remove server from known_hosts.

Parameters
server_ipServer IP address (IPv4 or IPv6, must not be NULL)
portServer port number
Returns
ASCIICHAT_OK on success, error code on failure

Removes all entries for server IP:port from known_hosts file. Removes both identity key entries and no-identity entries.

Note
Removal: Removes ALL entries matching IP:port (including multiple entries). File is rewritten with all matching entries removed.
File format: Removes entries matching <IP:port> x25519 ... and <IP:port> no-identity .... Uses proper bracket notation for IPv6 addresses.
File preservation: Preserves all other entries and comments. Only removes entries matching the specified IP:port.
Warning
File is rewritten: Function reads entire file, removes matching entries, and rewrites. Original file is preserved as backup if possible.

Definition at line 524 of file known_hosts.c.

524 {
525 // Validate parameters first
526 if (!server_ip) {
527 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameter: server_ip=%p",
528 server_ip);
529 }
530
531 const char *path = get_known_hosts_path();
532 int fd = platform_open("known_hosts_file", path, PLATFORM_O_RDONLY,
533 FILE_PERM_PRIVATE);
534 if (fd < 0) {
535 // File doesn't exist - nothing to remove, return success
536 return ASCIICHAT_OK;
537 }
538 FILE *f = platform_fdopen("known_hosts_stream", fd, "r");
539 defer(SAFE_FCLOSE(f));
540 if (!f) {
541 platform_close(fd);
542 SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open known hosts file: %s", path);
543 return ERROR_CONFIG;
544 }
545
546 // Format IP:port with proper bracket notation for IPv6
547 char ip_with_port[BUFFER_SIZE_MEDIUM];
548 if (format_ip_with_port(server_ip, port, ip_with_port,
549 sizeof(ip_with_port)) != ASCIICHAT_OK) {
550
551 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", server_ip);
552 }
553
554 // Read all lines into memory
555 char **lines = NULL;
556 size_t num_lines = 0;
557 defer({
558 if (lines) {
559 for (size_t i = 0; i < num_lines; i++) {
560 SAFE_FREE(lines[i]);
561 }
562 }
563 SAFE_FREE(lines);
564 });
565 char line[BUFFER_SIZE_XLARGE];
566
567 char expected_prefix[BUFFER_SIZE_MEDIUM];
568 safe_snprintf(expected_prefix, sizeof(expected_prefix), "%s ", ip_with_port);
569
570 while (fgets(line, sizeof(line), f)) {
571 // Skip lines that match this IP:port
572 if (strncmp(line, expected_prefix, strlen(expected_prefix)) != 0) {
573 // Keep this line
574 char **new_lines = SAFE_REALLOC(
575 (void *)lines, (num_lines + 1) * sizeof(char *), char **);
576 if (new_lines) {
577 lines = new_lines;
578 lines[num_lines] = platform_strdup(line);
579 if (lines[num_lines] == NULL) {
580 return SET_ERRNO(ERROR_MEMORY,
581 "Failed to duplicate line from known_hosts file");
582 }
583 num_lines++;
584 }
585 }
586 }
587 // Close first file before opening for write
588 if (f) {
589 fclose(f);
590 f = NULL; // Prevent double-close by defer
591 }
592
593 // Write back the filtered lines
594 fd = platform_open("known_hosts_file_write", path,
595 PLATFORM_O_WRONLY | PLATFORM_O_CREAT | PLATFORM_O_TRUNC,
596 FILE_PERM_PRIVATE);
597 f = platform_fdopen("known_hosts_write_stream", fd, "w");
598 if (!f) {
599 // Cleanup on error - fdopen failed, so fd is still open but f is NULL
600 // Individual line strings will be freed by defer cleanup
601 platform_close(fd); // Close fd directly since fdopen failed
602 return SET_ERRNO_SYS(ERROR_CONFIG, "Failed to open known hosts file: %s",
603 path);
604 }
605
606 for (size_t i = 0; i < num_lines; i++) {
607 (void)fputs(lines[i], f);
608 }
609 // All cleanup (lines, individual strings, file handle) handled by defer
610 // statements
611
612 log_debug("KNOWN_HOSTS: Successfully removed host from known_hosts file: %s",
613 path);
614 return ASCIICHAT_OK;
615}
#define SET_ERRNO_SYS(code,...)
#define SAFE_REALLOC(ptr, size, cast)
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_CONFIG
Definition error_codes.h:56
char * platform_strdup(const char *s)

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, BUFFER_SIZE_XLARGE, ERROR_CONFIG, ERROR_INVALID_PARAM, ERROR_MEMORY, format_ip_with_port(), get_known_hosts_path(), log_debug, platform_close(), platform_open(), platform_strdup(), SAFE_FCLOSE, SAFE_FREE, SAFE_REALLOC, SET_ERRNO, and SET_ERRNO_SYS.

◆ ssh_agent_add_key()

asciichat_error_t ssh_agent_add_key ( const private_key_t * private_key,
const char * key_path )

#include <include/ascii-chat/crypto/ssh/ssh_agent.h>

Add a private key to ssh-agent.

Parameters
private_keyPrivate key to add (must not be NULL)
key_pathOriginal key file path (for reference, can be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Adds private key to SSH agent using the SSH agent protocol.

Message format: uint32: message length byte: SSH2_AGENTC_ADD_IDENTITY (17) string: key type ("ssh-ed25519") string: public key (32 bytes) string: private key (64 bytes) string: comment (key path or empty)

Note
Agent requirement: SSH agent must be running and accessible. Function returns error if agent is not available.
Key format: Only Ed25519 keys are supported. Returns error if key type is not KEY_TYPE_ED25519.
Key addition: Uses SSH agent protocol directly via libplatform/pipe.h abstraction:
  • Connects to agent via Unix domain socket (POSIX) or named pipe (Windows)
  • Sends SSH2_AGENTC_ADD_IDENTITY (17) message with key material
  • Receives SSH_AGENT_SUCCESS (6) response on success
  • No temporary files or external commands required
Platform abstraction: Uses libplatform/pipe.h for cross-platform communication:
  • POSIX: Unix domain socket via SSH_AUTH_SOCK environment variable
  • Windows: Named pipe via SSH_AUTH_SOCK or default \\.\pipe\openssh-ssh-agent
Idempotent: SSH agent protocol is idempotent - adding same key multiple times is safe. Key is not duplicated in agent.
Key path: key_path is only used for logging/reference in agent comment field. No temporary files are created.
Warning
Agent requirement: SSH agent must be running and accessible. Returns error if agent connection fails (agent not running, wrong path, etc.).
Key format: Only Ed25519 keys are supported. Other key types will return error.

Definition at line 150 of file ssh_agent.c.

151 {
152 if (private_key == NULL) {
154 "Cannot add key to ssh-agent: private_key is NULL");
155 }
156 if (private_key->type != KEY_TYPE_ED25519) {
157 return SET_ERRNO(
159 "Cannot add key to ssh-agent: only Ed25519 keys supported");
160 }
161
162 log_debug("Adding key to ssh-agent: %s", key_path ? key_path : "(memory)");
163
164 // Open the pipe/socket for this operation (works on both Windows and Unix)
165 pipe_t pipe = ssh_agent_open_pipe();
166 if (pipe == INVALID_PIPE_VALUE) {
167 return SET_ERRNO(ERROR_CRYPTO, "Failed to connect to ssh-agent");
168 }
169
170 // Build SSH agent protocol message: SSH2_AGENTC_ADD_IDENTITY (17)
171 // Message format:
172 // uint32: message length
173 // byte: SSH2_AGENTC_ADD_IDENTITY (17)
174 // string: key type ("ssh-ed25519")
175 // string: public key (32 bytes)
176 // string: private key (64 bytes)
177 // string: comment (key path or empty)
178
179 unsigned char buf[BUFFER_SIZE_XXLARGE];
180 size_t pos = 4; // Reserve space for length prefix
181
182 // Message type: SSH2_AGENTC_ADD_IDENTITY
183 buf[pos++] = 17;
184
185 // Key type: "ssh-ed25519" (11 bytes)
186 uint32_t len = 11;
187 write_u32_be(buf + pos, len);
188 pos += 4;
189 // Binary protocol: intentionally not null-terminated
190 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary data
191 memcpy(buf + pos, "ssh-ed25519", 11);
192 pos += 11;
193
194 // Public key (32 bytes) - last 32 bytes of the 64-byte ed25519 key
195 len = 32;
196 write_u32_be(buf + pos, len);
197 pos += 4;
198 memcpy(buf + pos, private_key->key.ed25519 + ED25519_SEED_SIZE,
199 ED25519_PUBLIC_KEY_SIZE); // Public key is second half
200 pos += 32;
201
202 // Private key (64 bytes - full ed25519 key: 32-byte seed + 32-byte public)
203 len = 64;
204 write_u32_be(buf + pos, len);
205 pos += 4;
206 memcpy(buf + pos, private_key->key.ed25519, ED25519_PRIVATE_KEY_SIZE);
207 pos += 64;
208
209 // Comment (key path)
210 len = (uint32_t)(key_path ? strlen(key_path) : 0);
211
212 // SECURITY: Validate key path length to prevent buffer overflow
213 // Buffer is BUFFER_SIZE_XXLARGE (4096), pos is ~128 at this point, need 4
214 // bytes for length prefix
215 size_t max_key_path_len = sizeof(buf) - pos - 4;
216 if (len > max_key_path_len) {
217 platform_pipe_close(pipe);
218 sodium_memzero(buf, sizeof(buf));
220 "SSH key path too long: %u bytes (max %zu)", len,
221 max_key_path_len);
222 }
223
224 write_u32_be(buf + pos, len);
225 pos += 4;
226 if (len > 0) {
227 memcpy(buf + pos, key_path, len);
228 pos += len;
229 }
230
231 // Write message length at start (excluding the 4-byte length field itself)
232 uint32_t msg_len = (uint32_t)(pos - 4);
233 write_u32_be(buf, msg_len);
234
235 // Send message to agent
236 ssize_t bytes_written = platform_pipe_write(pipe, buf, pos);
237 if (bytes_written != (ssize_t)pos) {
238 platform_pipe_close(pipe);
239 sodium_memzero(buf, sizeof(buf));
240 return SET_ERRNO_SYS(ERROR_CRYPTO, "Failed to write to ssh-agent pipe");
241 }
242
243 // Read response
244 unsigned char response[BUFFER_SIZE_SMALL];
245 ssize_t bytes_read = platform_pipe_read(pipe, response, sizeof(response));
246 if (bytes_read < 5) {
247 platform_pipe_close(pipe);
248 sodium_memzero(buf, sizeof(buf));
249 return SET_ERRNO_SYS(ERROR_CRYPTO, "Failed to read from ssh-agent pipe");
250 }
251
252 // Done with the pipe - close it
253 platform_pipe_close(pipe);
254 sodium_memzero(buf, sizeof(buf));
255
256 // Check response: should be SSH_AGENT_SUCCESS (6)
257 // Response format: uint32 length, byte message_type
258 uint8_t response_type = response[4];
259 if (response_type == 6) {
260 log_debug("Successfully added key to ssh-agent");
261 return ASCIICHAT_OK;
262 } else if (response_type == 5) {
263 return SET_ERRNO(ERROR_CRYPTO,
264 "ssh-agent rejected key (SSH_AGENT_FAILURE)");
265 } else {
266 return SET_ERRNO(ERROR_CRYPTO, "ssh-agent returned unexpected response: %d",
267 response_type);
268 }
269}
#define BUFFER_SIZE_XXLARGE
Extra extra large buffer size (4096 bytes).
@ ERROR_BUFFER_OVERFLOW
#define ED25519_SEED_SIZE
Definition sizes.h:175
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:40

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, BUFFER_SIZE_XXLARGE, bytes_written, private_key_t::ed25519, ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, ED25519_SEED_SIZE, ERROR_BUFFER_OVERFLOW, ERROR_CRYPTO, ERROR_INVALID_PARAM, private_key_t::key, KEY_TYPE_ED25519, log_debug, SET_ERRNO, SET_ERRNO_SYS, and private_key_t::type.

◆ ssh_agent_get_key()

asciichat_error_t ssh_agent_get_key ( const public_key_t * public_key,
private_key_t * key_out )

#include <include/ascii-chat/crypto/ssh/ssh_agent.h>

Retrieve a private key from ssh-agent by matching public key.

Parameters
public_keyPublic key to match (must not be NULL)
key_outOutput private key structure (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Retrieves private key from SSH agent by sending SSH2_AGENTC_SIGN_REQUEST. This doesn't actually retrieve the private key material - instead it proves the key exists in the agent by attempting a signature operation.

Note
Agent requirement: SSH agent must be running and accessible. Returns error if agent is not available.
Key format: Only Ed25519 keys are supported.
Security: Private key never leaves ssh-agent. This function only verifies the key exists by matching the public key.

References ED25519_SIGNATURE_SIZE.

◆ ssh_agent_has_key()

bool ssh_agent_has_key ( const public_key_t * public_key)

#include <include/ascii-chat/crypto/ssh/ssh_agent.h>

Check if a public key is already in ssh-agent.

Parameters
public_keyPublic key to check (must not be NULL)
Returns
true if key is in agent, false otherwise

Checks if public key is already in SSH agent by listing agent keys using SSH agent protocol.

Note
Agent requirement: SSH agent must be running and accessible. Returns false if agent is not available.
Key listing: Uses SSH agent protocol directly via libplatform/pipe.h abstraction:
  • Connects to agent via Unix domain socket (POSIX) or named pipe (Windows)
  • Sends SSH2_AGENTC_REQUEST_IDENTITIES (11) message
  • Receives SSH2_AGENT_IDENTITIES_ANSWER (12) response with key list
  • Parses response to find matching Ed25519 public key (32-byte comparison)
Key matching: Compares raw Ed25519 public keys (32 bytes) directly. No fingerprint computation required - direct byte comparison.
Platform abstraction: Uses libplatform/pipe.h for cross-platform communication:
  • POSIX: Unix domain socket via SSH_AUTH_SOCK environment variable
  • Windows: Named pipe via SSH_AUTH_SOCK or default \\.\pipe\openssh-ssh-agent
Warning
Agent requirement: SSH agent must be running and accessible. Returns false if agent connection fails (agent not running, wrong path, etc.).

Definition at line 55 of file ssh_agent.c.

55 {
56 if (public_key == NULL) {
57 log_warn("NULL is not a valid public key");
58 return false;
59 }
60
61 // Use SSH agent protocol to list keys (works on both Windows and Unix)
62 pipe_t pipe = ssh_agent_open_pipe();
63 if (pipe == INVALID_PIPE_VALUE) {
64 return false;
65 }
66
67 // Build SSH2_AGENTC_REQUEST_IDENTITIES message (type 11)
68 unsigned char request[5];
69 request[0] = 0; // length: 1 (4-byte big-endian)
70 request[1] = 0;
71 request[2] = 0;
72 request[3] = 1;
73 request[4] = 11; // SSH2_AGENTC_REQUEST_IDENTITIES
74
75 // Send request
76 ssize_t bytes_written = platform_pipe_write(pipe, request, 5);
77 if (bytes_written != 5) {
78 platform_pipe_close(pipe);
79 return false;
80 }
81
82 // Read response
83 unsigned char response[BUFFER_SIZE_XXXLARGE];
84 ssize_t bytes_read = platform_pipe_read(pipe, response, sizeof(response));
85 if (bytes_read < 9) {
86 platform_pipe_close(pipe);
87 return false;
88 }
89
90 platform_pipe_close(pipe);
91
92 // Parse response: type should be SSH2_AGENT_IDENTITIES_ANSWER (12)
93 uint8_t resp_type = response[4];
94 if (resp_type != 12) {
95 return false;
96 }
97
98 // Number of keys at bytes 5-8
99 uint32_t num_keys = read_u32_be(response + 5);
100
101 // Parse keys and check if our public key matches
102 size_t pos = 9;
103 for (uint32_t i = 0; i < num_keys && pos + 4 < (size_t)bytes_read; i++) {
104 // Read key blob length
105 uint32_t blob_len = read_u32_be(response + pos);
106 pos += 4;
107
108 if (pos + blob_len > (size_t)bytes_read)
109 break;
110
111 // Parse the blob to extract the Ed25519 public key
112 size_t blob_pos = pos;
113 // Skip key type string
114 if (blob_pos + 4 > pos + blob_len) {
115 pos += blob_len;
116 continue;
117 }
118 uint32_t type_len = read_u32_be(response + blob_pos);
119 blob_pos += 4 + type_len;
120
121 // Read public key data
122 if (blob_pos + 4 > pos + blob_len) {
123 pos += blob_len;
124 continue;
125 }
126 uint32_t pubkey_len = read_u32_be(response + blob_pos);
127 blob_pos += 4;
128
129 // Compare public key (should be 32 bytes for Ed25519)
130 // Use constant-time comparison to prevent timing side channels
131 if (pubkey_len == 32 && blob_pos + 32 <= pos + blob_len) {
132 if (sodium_memcmp(response + blob_pos, public_key->key, 32) == 0) {
133 log_debug("Found matching key in ssh-agent");
134 return true;
135 }
136 }
137
138 pos += blob_len;
139
140 // Skip comment string length + comment
141 if (pos + 4 > (size_t)bytes_read)
142 break;
143 uint32_t comment_len = read_u32_be(response + pos);
144 pos += 4 + comment_len;
145 }
146
147 return false;
148}
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:85

References BUFFER_SIZE_XXXLARGE, bytes_written, public_key_t::key, log_debug, and log_warn.

◆ ssh_agent_is_available()

bool ssh_agent_is_available ( void )

#include <include/ascii-chat/crypto/ssh/ssh_agent.h>

Check if ssh-agent is running and available.

Returns
true if ssh-agent is available, false otherwise

Checks if SSH agent is running and accessible by verifying SSH_AUTH_SOCK environment variable.

Note
Agent detection:
  • Checks SSH_AUTH_SOCK environment variable is set
  • On Unix: Verifies socket exists and is accessible (access() with W_OK)
  • On Windows: Only checks environment variable (named pipe accessibility checked at connection time)
Platform differences:
  • Unix: Uses Unix domain socket (AF_UNIX) - can verify socket exists
  • Windows: Uses named pipe - can't use access() on named pipes
Agent location:
  • Unix: SSH_AUTH_SOCK points to Unix domain socket (e.g., /tmp/ssh-XXXXXXXX/agent.XXXXXX)
  • Windows: SSH_AUTH_SOCK points to named pipe (e.g., \\.\pipe\openssh-ssh-agent)
Warning
Agent may not be running: Function checks environment variable but doesn't verify agent is actually running. Connection may fail later if agent is not running.
Windows limitation: Cannot verify named pipe accessibility without attempting connection. Function may return true even if agent is not running (connection will fail later).

Definition at line 43 of file ssh_agent.c.

43 {
44 /* Try to open the SSH agent connection */
45 pipe_t pipe = ssh_agent_open_pipe();
46 if (pipe != INVALID_PIPE_VALUE) {
47 platform_pipe_close(pipe);
48 log_dev("ssh-agent is available");
49 return true;
50 }
51 log_dev("ssh-agent not available");
52 return false;
53}

References log_dev.

◆ ssh_agent_sign()

asciichat_error_t ssh_agent_sign ( const public_key_t * public_key,
const uint8_t * message,
size_t message_len,
uint8_t signature[64] )

#include <include/ascii-chat/crypto/ssh/ssh_agent.h>

Sign data using SSH agent with the specified public key.

Parameters
public_keyPublic key to use for signing (must not be NULL)
messageData to sign (must not be NULL)
message_lenLength of data to sign
signatureOutput buffer for signature (must be 64 bytes for Ed25519)
Returns
ASCIICHAT_OK on success, error code on failure

Signs message data using SSH agent protocol SSH2_AGENTC_SIGN_REQUEST (message type 13).

Note
Agent requirement: SSH agent must be running and accessible, and must have the private key corresponding to public_key.
Only Ed25519 signatures are supported (64 bytes).
The public key must already be in the ssh-agent (check with ssh_agent_has_key first).

Definition at line 271 of file ssh_agent.c.

273 {
274 if (!public_key || !message || !signature) {
275 return SET_ERRNO(
277 "Invalid parameters: public_key=%p, message=%p, signature=%p",
278 public_key, message, signature);
279 }
280
281 if (public_key->type != KEY_TYPE_ED25519) {
283 "Only Ed25519 keys are supported for SSH agent signing");
284 }
285
286 // SSH agent protocol limits message size (typical OpenSSH agent limit is
287 // around 1MB) Large messages can cause agent memory exhaustion or timeout
288 if (message_len > 1024 * 1024) {
289 return SET_ERRNO(ERROR_CRYPTO, "Message too large for SSH agent (max 1MB)");
290 }
291
292 // Connect to SSH agent
293 pipe_t pipe = ssh_agent_open_pipe();
294 if (pipe == INVALID_PIPE_VALUE) {
295 return SET_ERRNO(ERROR_CRYPTO, "Cannot connect to ssh-agent");
296 }
297
298 // Build SSH2_AGENTC_SIGN_REQUEST message (type 13)
299 // Format: uint32 length, byte type, string key_blob, string data, uint32
300 // flags For Ed25519, key_blob is: string "ssh-ed25519", string public_key(32
301 // bytes)
302
303 const char *key_type = "ssh-ed25519";
304 uint32_t key_type_len = (uint32_t)strlen(key_type);
305
306 // Calculate total message length
307 // 1 (type) + 4 (key_blob_len) + key_blob_size + 4 (data_len) + data_size + 4
308 // (flags)
309 uint32_t key_blob_size =
310 4 + key_type_len + 4 + 32; // string(key_type) + string(pubkey)
311 uint32_t total_len = 1 + 4 + key_blob_size + 4 + (uint32_t)message_len + 4;
312
313 uint8_t *buf = SAFE_MALLOC(total_len + 4, uint8_t *); // +4 for length prefix
314 if (!buf) {
315 platform_pipe_close(pipe);
316 return SET_ERRNO(ERROR_CRYPTO, "Out of memory for SSH agent sign request");
317 }
318
319 uint32_t offset = 0;
320
321 // Write total message length (excluding this 4-byte length field)
322 write_u32_be(buf + offset, total_len);
323 offset += 4;
324
325 // Write message type (13 = SSH2_AGENTC_SIGN_REQUEST)
326 buf[offset++] = 13;
327
328 // Write key_blob length
329 write_u32_be(buf + offset, key_blob_size);
330 offset += 4;
331
332 // Write key_blob: string(key_type)
333 write_u32_be(buf + offset, key_type_len);
334 offset += 4;
335 // NOLINTNEXTLINE(bugprone-not-null-terminated-result) - binary data
336 memcpy(buf + offset, key_type, key_type_len);
337 offset += key_type_len;
338
339 // Write key_blob: string(public_key)
340 write_u32_be(buf + offset, 32);
341 offset += 4;
342 memcpy(buf + offset, public_key->key, ED25519_PUBLIC_KEY_SIZE);
343 offset += 32;
344
345 // Write data to sign
346 write_u32_be(buf + offset, (uint32_t)message_len);
347 offset += 4;
348 memcpy(buf + offset, message, message_len);
349 offset += (uint32_t)message_len;
350
351 // Write flags (0 = default)
352 write_u32_be(buf + offset, 0);
353 offset += 4;
354
355 // Send request
356 ssize_t written = platform_pipe_write(pipe, buf, total_len + 4);
357 sodium_memzero(buf, total_len + 4);
358 SAFE_FREE(buf);
359
360 if (written < 0 || (size_t)written != total_len + 4) {
361 platform_pipe_close(pipe);
362 return SET_ERRNO(ERROR_CRYPTO, "Failed to write SSH agent sign request");
363 }
364
365 // Read response
367 ssize_t read_bytes = platform_pipe_read(pipe, response, sizeof(response));
368 platform_pipe_close(pipe);
369
370 if (read_bytes < 5) {
371 return SET_ERRNO(ERROR_CRYPTO,
372 "Failed to read SSH agent sign response (read %zd bytes)",
373 read_bytes);
374 }
375
376 // Response format: uint32 length, byte type, data...
377 // We validate length implicitly by checking read_bytes and parsing the full
378 // response
379 (void)read_u32_be(response); // Read but don't need explicit length check
380 uint8_t response_type = response[4];
381
382 // Check for SSH2_AGENT_SIGN_RESPONSE (14)
383 if (response_type != 14) {
384 if (response_type == 5) {
385 return SET_ERRNO(ERROR_CRYPTO,
386 "ssh-agent refused to sign (SSH_AGENT_FAILURE)");
387 }
388 return SET_ERRNO(
390 "ssh-agent returned unexpected response type: %d (expected 14)",
391 response_type);
392 }
393
394 // Parse signature blob
395 // Response format: uint32 len, byte type(14), string signature_blob
396 if (read_bytes < 9) {
397 return SET_ERRNO(ERROR_CRYPTO,
398 "SSH agent response too short (no signature blob length)");
399 }
400
401 uint32_t sig_blob_len = read_u32_be(response + 5);
402 uint32_t expected_total = 4 + 1 + 4 + sig_blob_len;
403
404 if ((size_t)read_bytes < expected_total) {
405 return SET_ERRNO(
407 "SSH agent response truncated (expected %u bytes, got %zd)",
408 expected_total, read_bytes);
409 }
410
411 // Signature blob format for Ed25519: string "ssh-ed25519", string
412 // signature(64 bytes)
413 uint32_t offset_sig = 9;
414 uint32_t sig_type_len = read_u32_be(response + offset_sig);
415 offset_sig += 4;
416
417 if (offset_sig + sig_type_len + 4 > (uint32_t)read_bytes) {
418 return SET_ERRNO(ERROR_CRYPTO,
419 "SSH agent signature blob truncated at signature type");
420 }
421
422 // Verify signature type is "ssh-ed25519"
423 if (sig_type_len != 11 ||
424 memcmp(response + offset_sig, "ssh-ed25519", 11) != 0) {
425 return SET_ERRNO(ERROR_CRYPTO, "SSH agent returned non-Ed25519 signature");
426 }
427 offset_sig += sig_type_len;
428
429 // Read signature bytes
430 uint32_t sig_len = read_u32_be(response + offset_sig);
431 offset_sig += 4;
432
433 if (sig_len != 64) {
434 return SET_ERRNO(
436 "SSH agent returned invalid Ed25519 signature length: %u (expected 64)",
437 sig_len);
438 }
439
440 if (offset_sig + 64 > (uint32_t)read_bytes) {
441 return SET_ERRNO(ERROR_CRYPTO,
442 "SSH agent signature blob truncated at signature bytes");
443 }
444
445 // Copy signature to output
446 memcpy(signature, response + offset_sig, ED25519_SIGNATURE_SIZE);
447
448 log_debug("SSH agent successfully signed %zu bytes with Ed25519 key",
449 message_len);
450 return ASCIICHAT_OK;
451}
key_type_t type
Definition key_types.h:84

References ASCIICHAT_OK, BUFFER_SIZE_XXLARGE, ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE, ERROR_CRYPTO, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, public_key_t::key, KEY_TYPE_ED25519, log_debug, SAFE_FREE, SAFE_MALLOC, SET_ERRNO, and public_key_t::type.

Referenced by ed25519_sign_message().

Variable Documentation

◆ buf

br_x509_trust_anchor* anchor_list::buf

Array of trust anchors (dynamically allocated)

Definition at line 89 of file pem.h.

Referenced by https_get().

◆ len

size_t anchor_list::len

Total capacity of array

Definition at line 91 of file pem.h.

◆ ptr

size_t anchor_list::ptr

Current number of trust anchors

Definition at line 90 of file pem.h.

Referenced by https_get().