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

🔑 SSH key, GPG key, and key validation APIs More...

Data Structures

struct  public_key_t
 The normalized public identity used by ascii-chat's crypto and key-management code. More...
struct  private_key_t
 Private identity-key material used for server authentication and signing. More...

Typedefs

typedef struct crypto_handshake_context_t crypto_handshake_context_t
 Cryptographic handshake context structure.

Variables

key_type_t public_key_t::type
uint8_t public_key_t::key [CRYPTO_PUBLIC_KEY_SIZE]
char public_key_t::comment [MAX_COMMENT_LEN]
key_type_t private_key_t::type
uint8_t   private_key_t::ed25519 [ED25519_PRIVATE_KEY_SIZE] 
uint8_t   private_key_t::x25519 [X25519_KEY_SIZE] 
union { 
   uint8_t   private_key_t::ed25519 [ED25519_PRIVATE_KEY_SIZE] 
   uint8_t   private_key_t::x25519 [X25519_KEY_SIZE] 
} private_key_t::key
bool private_key_t::use_ssh_agent
bool private_key_t::use_gpg_agent
uint8_t private_key_t::public_key [CRYPTO_PUBLIC_KEY_SIZE]
char private_key_t::key_comment [MAX_COMMENT_LEN]
char private_key_t::gpg_keygrip [MAX_GPG_KEYGRIP_LEN]

Key Type Definitions

The normalized public identity used by ascii-chat's crypto and key-management code

enum  key_type_t { KEY_TYPE_UNKNOWN = 0 , KEY_TYPE_ED25519 , KEY_TYPE_X25519 , KEY_TYPE_GPG }
 Key type enumeration. More...

GPG Key Parsing

asciichat_error_t parse_gpg_key (const char *gpg_key_text, public_key_t *key_out)
 Parse GPG key from armored text format.
asciichat_error_t parse_gpg_key_binary (const uint8_t *gpg_key_binary, size_t key_size, public_key_t *key_out)
 Parse GPG key from binary format.
asciichat_error_t validate_gpg_key_format (const char *gpg_key_text)
 Validate GPG key format and structure.
asciichat_error_t extract_ed25519_from_gpg (const char *gpg_key_text, uint8_t ed25519_pk[32])
 Extract Ed25519 public key from GPG key.
asciichat_error_t gpg_to_x25519_public (const char *gpg_key_text, uint8_t x25519_pk[32])
 Convert GPG key to X25519 for key exchange.

GPG Key Operations

asciichat_error_t get_gpg_fingerprint (const char *gpg_key_text, uint8_t fingerprint_out[20])
 Get GPG key fingerprint.
asciichat_error_t get_gpg_key_id (const char *gpg_key_text, uint8_t key_id_out[8])
 Get GPG key ID (short fingerprint).
asciichat_error_t check_gpg_key_expiry (const char *gpg_key_text, bool *is_expired)
 Check if GPG key is expired.

GPG Key Formatting

asciichat_error_t format_gpg_key_display (const char *gpg_key_text, char *output, size_t output_size)
 Format GPG key for display.
asciichat_error_t extract_gpg_key_comment (const char *gpg_key_text, char *comment_out, size_t comment_size)
 Extract key comment/email from GPG key.

HTTPS Key Fetching

Fetch SSH/GPG keys from GitHub and GitLab using HTTPS (BearSSL). Requires network connectivity and valid usernames.

asciichat_error_t fetch_github_ssh_keys (const char *username, char ***keys_out, size_t *num_keys)
 Fetch SSH keys from GitHub using HTTPS.
asciichat_error_t fetch_gitlab_ssh_keys (const char *username, char ***keys_out, size_t *num_keys)
 Fetch SSH keys from GitLab using HTTPS.
asciichat_error_t fetch_github_gpg_keys (const char *username, char ***keys_out, size_t *num_keys)
 Fetch GPG keys from GitHub using HTTPS.
asciichat_error_t fetch_gitlab_gpg_keys (const char *username, char ***keys_out, size_t *num_keys)
 Fetch GPG keys from GitLab using HTTPS.

Key Parsing from HTTPS Responses

asciichat_error_t parse_ssh_keys_from_response (const char *response_text, size_t response_len, char ***keys_out, size_t *num_keys, size_t max_keys)
 Parse SSH keys from HTTPS response text.
asciichat_error_t parse_gpg_keys_from_response (const char *response_text, size_t response_len, char ***keys_out, size_t *num_keys, size_t max_keys)
 Parse GPG keys from HTTPS response text.

URL Construction

asciichat_error_t build_github_ssh_url (const char *username, char *url_out, size_t url_size)
 Construct GitHub SSH keys URL.
asciichat_error_t build_gitlab_ssh_url (const char *username, char *url_out, size_t url_size)
 Construct GitLab SSH keys URL.
asciichat_error_t build_github_gpg_url (const char *username, char *url_out, size_t url_size)
 Construct GitHub GPG keys URL.
asciichat_error_t build_gitlab_gpg_url (const char *username, char *url_out, size_t url_size)
 Construct GitLab GPG keys URL.

Public Key Parsing

asciichat_error_t parse_public_key (const char *input, public_key_t *key_out)
 Parse SSH/GPG public key from any format (returns first key only).
asciichat_error_t parse_public_keys (const char *input, public_key_t *keys_out, size_t *num_keys, size_t max_keys)
 Parse all SSH/GPG public keys from any format (returns all keys).

Private Key Parsing

asciichat_error_t parse_private_key (const char *path, private_key_t *key_out)
 Parse SSH private key from file.

Key Conversion

asciichat_error_t public_key_to_x25519 (const public_key_t *key, uint8_t x25519_pk[32])
 Convert public key to X25519 for Diffie-Hellman key exchange.
asciichat_error_t private_key_to_x25519 (const private_key_t *key, uint8_t x25519_sk[32])
 Convert private key to X25519 for Diffie-Hellman key exchange.

Ed25519 Signing and Verification

asciichat_error_t ed25519_sign_message (const private_key_t *key, const uint8_t *message, size_t message_len, uint8_t signature[64])
 Sign a message with Ed25519 (uses SSH agent if available, otherwise in-memory key).
asciichat_error_t ed25519_verify_signature (const uint8_t public_key[32], const uint8_t *message, size_t message_len, const uint8_t signature[64], const char *gpg_key_id)
 Verify an Ed25519 signature.

Key Fetching (GitHub/GitLab)

Fetch SSH/GPG keys from GitHub and GitLab using HTTPS (BearSSL). Requires network connectivity and valid usernames.

asciichat_error_t fetch_github_keys (const char *username, char ***keys_out, size_t *num_keys, bool use_gpg)
 Fetch SSH/GPG keys from GitHub using BearSSL.
asciichat_error_t fetch_gitlab_keys (const char *username, char ***keys_out, size_t *num_keys, bool use_gpg)
 Fetch SSH/GPG keys from GitLab using BearSSL.

Key Parsing

asciichat_error_t parse_keys_from_file (const char *path, public_key_t *keys, size_t *num_keys, size_t max_keys)
 Parse SSH keys from file (supports authorized_keys and known_hosts formats).

Key Formatting and Utilities

void format_public_key (const public_key_t *key, char *output, size_t output_size)
 Convert public key to display format (ssh-ed25519 or x25519 hex).
asciichat_error_t hex_decode (const char *hex, uint8_t *output, size_t output_len)
 Decode hex string to binary (utility function for testing).
asciichat_error_t validate_ssh_key_file (const char *key_path)
 Validate SSH key file before parsing.

Key Validation

asciichat_error_t validate_public_key (const public_key_t *key)
 Validate a public key structure.
asciichat_error_t validate_private_key (const private_key_t *key)
 Validate a private key structure.
asciichat_error_t check_key_expiry (const public_key_t *key, bool *is_expired)
 Check if a key is expired.
asciichat_error_t validate_key_security (const char *key_path)
 Validate key permissions and security.

Key Format Validation

asciichat_error_t validate_ssh_key_format (const char *key_text)
 Validate SSH key format.
asciichat_error_t validate_x25519_key_format (const char *key_hex)
 Validate X25519 key format.

Key Security Checks

asciichat_error_t check_key_strength (const public_key_t *key, bool *is_weak)
 Check if key has weak parameters.
asciichat_error_t check_key_patterns (const public_key_t *key, bool *has_weak_patterns)
 Check for key reuse or weak patterns.

Key Comparison and Matching

asciichat_error_t compare_public_keys (const public_key_t *key1, const public_key_t *key2, bool *are_equal)
 Compare two public keys for equality.
asciichat_error_t check_key_fingerprint (const public_key_t *key, const uint8_t *fingerprint, size_t fingerprint_len, bool *matches)
 Check if key matches a fingerprint.
asciichat_error_t generate_key_fingerprint (const public_key_t *key, uint8_t *fingerprint_out, size_t fingerprint_size)
 Generate key fingerprint.

SSH Key Parsing

asciichat_error_t parse_ssh_ed25519_line (const char *line, uint8_t ed25519_pk[32])
 Parse SSH Ed25519 public key from "ssh-ed25519 AAAAC3..." format.
asciichat_error_t parse_ssh_private_key (const char *key_path, private_key_t *key_out)
 Parse SSH Ed25519 private key from file.

Key Conversion

asciichat_error_t ed25519_to_x25519_public (const uint8_t ed25519_pk[32], uint8_t x25519_pk[32])
 Convert Ed25519 public key to X25519 for key exchange.
asciichat_error_t ed25519_to_x25519_private (const uint8_t ed25519_sk[64], uint8_t x25519_sk[32])
 Convert Ed25519 private key to X25519 for key exchange.

Detailed Description

🔑 SSH key, GPG key, and key validation APIs

SSH key, GPG key, and key validation APIs.

This module handles GPG key parsing, validation, and conversion to X25519 for key exchange operations.

Warning
GPG SUPPORT IS CURRENTLY DISABLED: This code exists but many functions are not fully implemented. GPG key parsing may not work until GPG support is re-enabled and functions are completed.
Note
Key format: Only Ed25519 GPG keys are supported. RSA/ECDSA GPG keys are NOT supported.
Key conversion: GPG Ed25519 keys are extracted and converted to X25519 for key exchange using libsodium's conversion functions.
OpenPGP format: Functions parse OpenPGP packet structure to extract Ed25519 public keys from GPG keys.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This module handles fetching SSH and GPG keys from GitHub and GitLab using HTTPS requests with BearSSL for secure communication.

Note
Network operations: Requires network connectivity and valid usernames. May fail if network is unavailable or usernames don't exist.
TLS security: Uses BearSSL for HTTPS connections with system CA certificates. Validates server certificates against system trust store.
Key format: Only Ed25519 SSH keys are parsed from responses. Other key types (RSA, ECDSA) are skipped.
GPG support: GPG key fetching code exists but GPG parsing may not work until GPG support is re-enabled.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header contains the core key type definitions that can be shared between the main keys.h and the specialized key modules without circular dependencies.

All keys in this system are 32 bytes - Ed25519, X25519, and GPG-derived keys. This fixed size simplifies protocol design and key management.

Note
Key Type Restriction: Only Ed25519 and X25519 are supported. RSA and ECDSA are NOT supported due to libsodium limitations and protocol design requiring fixed-size keys.
GPG Support: GPG keys are parsed and converted to Ed25519/X25519 format. GPG agent support exists but is currently disabled.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This header provides a unified interface for parsing SSH, GPG, and X25519 keys from various sources including files, URLs, and raw formats.

Supported input formats:

  • SSH Ed25519 keys (ssh-ed25519 format)
  • GitHub/GitLab SSH keys (fetched via HTTPS)
  • GPG Ed25519 keys (from local keyring via gpg-agent)
  • X25519 keys (raw hex or base64)
  • File paths (reads first line and parses)
Note
All keys are normalized to 32-byte X25519 format for key exchange.
GPG support: GPG Ed25519 keys are fully supported via gpg-agent (requires gpg binary in PATH).
GitHub/GitLab fetching: Uses BearSSL for HTTPS requests.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This module provides comprehensive key validation, security checks, and format verification for all supported key types.

Note
Key validation: Validates key structure, format, and security properties. Used before key operations to ensure keys are valid and secure.
Security checks: Includes permission checking, weak key detection, and pattern analysis for security vulnerabilities.
Key format validation: Validates SSH, GPG, and X25519 key formats. Returns error early if format is invalid.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

This module handles SSH Ed25519 key parsing, validation, and conversion to X25519 for key exchange operations.

Note
Key format: Only Ed25519 keys are supported. RSA/ECDSA keys are NOT supported.
OpenSSH format: Supports OpenSSH private key format (openssh-key-v1). Supports encrypted and unencrypted keys.
Key conversion: Ed25519 keys are converted to X25519 for key exchange using libsodium's conversion functions.
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
October 2025

Key Management README

Overview

The Keys Module module provides comprehensive support for parsing, validating, and managing cryptographic keys from multiple sources and formats. It serves as the foundation for secure authentication and key exchange in ascii-chat.

Implementation: lib/crypto/keys/

Key Features:

  • Unified key parsing from multiple sources (SSH, GPG, raw formats)
  • Support for multiple key sources (files, GitHub, GitLab, raw hex/base64)
  • Automatic key format detection and conversion
  • Key validation and security checks
  • SSH agent integration for secure signing
  • Ed25519 to X25519 conversion for key exchange

Supported Key Formats

SSH Ed25519 Keys

Format: OpenSSH Ed25519 public and private keys

Public Key Format:

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... comment

Private Key Format:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

Supported Operations:

  • Parse SSH public key from string
  • Parse SSH private key from file
  • Validate key file permissions
  • Support for encrypted private keys (with password prompt)
  • Convert Ed25519 to X25519 for key exchange

Example:

// Parse SSH public key from string
public_key_t pubkey;
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... alice@example.com",
&pubkey
);
// Parse SSH private key from file
private_key_t privkey;
err = parse_private_key("~/.ssh/id_ed25519", &privkey);
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
asciichat_error_t parse_private_key(const char *key_path, private_key_t *key_out)
Parse SSH private key from file.
Definition keys.c:212
asciichat_error_t parse_public_key(const char *input, public_key_t *key_out)
Parse SSH/GPG public key from any format (returns first key only).
Definition keys.c:36
Private identity-key material used for server authentication and signing.
Definition key_types.h:101
The normalized public identity used by ascii-chat's crypto and key-management code.
Definition key_types.h:76

GPG Keys

Format: OpenPGP armored format (PEM-style)

Key Format:

-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----

Supported Operations:

  • Parse GPG public key from keyring via gpg --list-keys and keygrip
  • Extract Ed25519 public key via gpg-agent READKEY command
  • Sign challenges using gpg-agent PKSIGN command (Assuan protocol)
  • Verify signatures using gpg --verify for deterministic Ed25519
  • Convert GPG Ed25519 keys to X25519 for key exchange
  • Accept 8, 16, or 40 character key IDs (short, long, full fingerprint)

Requirements:

  • Only Ed25519 GPG keys are supported (not RSA/DSA)
  • gpg binary must be in PATH
  • gpg-agent must be running for signing operations

Example:

// Parse GPG key by key ID
private_key_t privkey;
"gpg:897607FA43DC66F612710AF97FE90A79F2E80ED3",
&privkey
);
// Parse GPG key for server verification
public_key_t pubkey;
"gpg:897607FA43DC66F612710AF97FE90A79F2E80ED3",
&pubkey
);

Raw X25519 Keys

Format: 64 hex characters or base64-encoded 32-byte key

Supported Formats:

  • Hex: 1234567890abcdef... (64 hex chars for 32 bytes)
  • Base64: Base64-encoded 32-byte key

Example:

// Parse raw X25519 key from hex
public_key_t pubkey;
"1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
&pubkey
);

Key Sources

Local Files

Keys can be loaded from local files:

Public Keys:

// Load from .pub file (reads first line)
public_key_t pubkey;
asciichat_error_t err = parse_public_key("~/.ssh/id_ed25519.pub", &pubkey);
// Or read first line and parse manually
FILE *f = fopen("~/.ssh/id_ed25519.pub", "r");
char line[1024];
fgets(line, sizeof(line), f);
err = parse_public_key(line, &pubkey);
fclose(f);
// Load multiple keys from file (one per line)
public_key_t keys[10];
size_t num_keys;
err = parse_keys_from_file("~/.ssh/authorized_keys", keys, &num_keys, 10);
// File can contain multiple keys, one per line:
// ssh-ed25519 AAAAC3... alice@example.com
// ssh-ed25519 AAAAC3... bob@example.com
asciichat_error_t parse_keys_from_file(const char *path, public_key_t *keys, size_t *num_keys, size_t max_keys)
Parse SSH keys from file (supports authorized_keys and known_hosts formats).
Definition keys.c:599

Private Keys:

// Load private key from file
private_key_t privkey;
asciichat_error_t err = parse_private_key("~/.ssh/id_ed25519", &privkey);
// File permissions are validated (warns if overly permissive)
// Encrypted keys prompt for password automatically

GitHub and GitLab Integration

Keys can be fetched directly from GitHub or GitLab using HTTPS:

SSH Keys:

// Fetch SSH keys from GitHub
char **keys;
size_t num_keys;
asciichat_error_t err = fetch_github_ssh_keys("username", &keys, &num_keys);
if (err == ASCIICHAT_OK && num_keys > 0) {
// Parse first Ed25519 key
public_key_t pubkey;
parse_public_key(keys[0], &pubkey);
// Free keys array
for (size_t i = 0; i < num_keys; i++) {
free(keys[i]);
}
free(keys);
}
@ ASCIICHAT_OK
Definition error_codes.h:50
asciichat_error_t fetch_github_ssh_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch SSH keys from GitHub using HTTPS.
Definition https_keys.c:173

GPG Keys:

// Fetch GPG keys from GitHub
char **keys;
size_t num_keys;
asciichat_error_t err = fetch_github_gpg_keys("username", &keys, &num_keys);
asciichat_error_t fetch_github_gpg_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch GPG keys from GitHub using BearSSL.
Definition https_keys.c:233

GitLab Support:

// Fetch SSH keys from GitLab
err = fetch_gitlab_ssh_keys("username", &keys, &num_keys);
// Fetch GPG keys from GitLab
err = fetch_gitlab_gpg_keys("username", &keys, &num_keys);
asciichat_error_t fetch_gitlab_gpg_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch GPG keys from GitLab using BearSSL.
Definition https_keys.c:263
asciichat_error_t fetch_gitlab_ssh_keys(const char *username, char ***keys_out, size_t *num_keys)
Fetch SSH keys from GitLab using HTTPS.
Definition https_keys.c:203

Unified Parsing:

// Parse key from GitHub using unified interface
public_key_t pubkey;
asciichat_error_t err = parse_public_key("github:username", &pubkey);
// Automatically fetches from https://github.com/username.keys
// Uses first Ed25519 key found
// Parse GPG key from GitHub
err = parse_public_key("github:username.gpg", &pubkey);
// Parse from GitLab
err = parse_public_key("gitlab:username", &pubkey);
err = parse_public_key("gitlab:username.gpg", &pubkey);

Unified Key Parsing

The parse_public_key() function supports multiple input formats automatically:

public_key_t pubkey;
// SSH Ed25519 format
err = parse_public_key("ssh-ed25519 AAAAC3... comment", &pubkey);
// GitHub SSH keys
err = parse_public_key("github:username", &pubkey);
// GitLab SSH keys
err = parse_public_key("gitlab:username", &pubkey);
// GitHub GPG keys
err = parse_public_key("github:username.gpg", &pubkey);
// File path
err = parse_public_key("~/.ssh/id_ed25519.pub", &pubkey);
// Raw hex
err = parse_public_key("1234567890abcdef...", &pubkey);

Key Validation

Public Key Validation

All public keys are validated before use:

public_key_t pubkey;
asciichat_error_t err = parse_public_key(input, &pubkey);
// Validate key structure
err = validate_public_key(&pubkey);
if (err != ASCIICHAT_OK) {
log_error("Invalid public key");
return err;
}
asciichat_error_t validate_public_key(const public_key_t *key)
Validate a public key structure.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628

Validation Checks:

  • Key type is valid (Ed25519, X25519, or GPG)
  • Key data is not all zeros
  • Comment length is within limits (< 256 chars)
  • Key size matches type (32 bytes for Ed25519/X25519)

Private Key Validation

Private keys are validated similarly:

private_key_t privkey;
asciichat_error_t err = parse_private_key("~/.ssh/id_ed25519", &privkey);
// Validate key structure
err = validate_private_key(&privkey);
if (err != ASCIICHAT_OK) {
log_error("Invalid private key");
return err;
}
asciichat_error_t validate_private_key(const private_key_t *key)
Validate a private key structure.

Validation Checks:

  • Key type is valid (Ed25519 or X25519)
  • Key data is not all zeros
  • Key size matches type (32 bytes for X25519, 64 bytes for Ed25519)
  • Comment length is within limits

File Permission Validation

Private key files are checked for appropriate permissions:

// Validate SSH key file before parsing
asciichat_error_t err = validate_ssh_key_file("~/.ssh/id_ed25519");
// Checks:
// - File exists and is readable
// - File has valid SSH private key header
// - File permissions are appropriate (warns if overly permissive)
asciichat_error_t validate_ssh_key_file(const char *key_path)
Validate SSH key file permissions and format.
Definition ssh_keys.c:1007

Permission Recommendations:

  • Private keys should have restrictive permissions (0600 on Unix)
  • Function warns if file has world-readable permissions
  • Permission checking is Unix-specific (Windows doesn't have Unix-style permissions)

Key Conversion

Ed25519 to X25519 Conversion

Ed25519 keys are converted to X25519 format for Diffie-Hellman key exchange:

Public Key Conversion:

// Parse Ed25519 public key
public_key_t ed25519_pubkey;
parse_public_key("ssh-ed25519 AAAAC3...", &ed25519_pubkey);
// Convert to X25519 for key exchange
uint8_t x25519_pk[32];
asciichat_error_t err = public_key_to_x25519(&ed25519_pubkey, x25519_pk);
// Use x25519_pk for Diffie-Hellman key exchange
unsigned char uint8_t
asciichat_error_t public_key_to_x25519(const public_key_t *key, uint8_t x25519_pk[X25519_KEY_SIZE])
Definition keys.c:529

Private Key Conversion:

// Parse Ed25519 private key
private_key_t ed25519_privkey;
parse_private_key("~/.ssh/id_ed25519", &ed25519_privkey);
// Convert to X25519 for key exchange
uint8_t x25519_sk[32];
asciichat_error_t err = private_key_to_x25519(&ed25519_privkey, x25519_sk);
// Use x25519_sk for Diffie-Hellman key exchange
asciichat_error_t private_key_to_x25519(const private_key_t *key, uint8_t x25519_sk[X25519_KEY_SIZE])
Definition keys.c:548

Conversion Details:

  • Uses libsodium's conversion functions (crypto_sign_ed25519_pk_to_curve25519)
  • Mathematically safe (same curve, different representation)
  • Both Ed25519 and X25519 keys are 32 bytes
  • Ed25519 private keys are 64 bytes (seed + public), extracts 32-byte seed for conversion

Direct Conversion Functions

Lower-level conversion functions are also available:

// Direct Ed25519 public key conversion
uint8_t ed25519_pk[32] = {...};
uint8_t x25519_pk[32];
asciichat_error_t err = ed25519_to_x25519_public(ed25519_pk, x25519_pk);
// Direct Ed25519 private key conversion
uint8_t ed25519_sk[64] = {...}; // seed + public
uint8_t x25519_sk[32];
asciichat_error_t err = ed25519_to_x25519_private(ed25519_sk, x25519_sk);
asciichat_error_t ed25519_to_x25519_private(const uint8_t ed25519_sk[ED25519_PRIVATE_KEY_SIZE], uint8_t x25519_sk[X25519_KEY_SIZE])
Definition ssh_keys.c:1092
asciichat_error_t ed25519_to_x25519_public(const uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t x25519_pk[X25519_KEY_SIZE])
Definition ssh_keys.c:1079

Signing and Verification

Signing Messages

Messages can be signed with Ed25519 private keys:

// Load private key
private_key_t privkey;
parse_private_key("~/.ssh/id_ed25519", &privkey);
// Sign message
const uint8_t message[] = "Hello, secure world!";
uint8_t signature[64];
&privkey,
message,
sizeof(message) - 1, // Length without null terminator
signature
);
// Use signature...
asciichat_error_t ed25519_sign_message(const private_key_t *key, const uint8_t *message, size_t message_len, uint8_t signature[ED25519_SIGNATURE_SIZE])
Definition ssh_keys.c:1109

SSH Agent Support:

// If SSH agent is available, signing uses agent
// Key stays in agent (not loaded into memory)
// More secure - private key never touches application memory
// Configure key to use SSH agent
privkey.use_ssh_agent = true;
// Signing now uses SSH agent protocol
ed25519_sign_message(&privkey, message, message_len, signature);
bool use_ssh_agent
Definition key_types.h:107

Verifying Signatures

Signatures can be verified with Ed25519 public keys:

// Load public key
public_key_t pubkey;
parse_public_key("ssh-ed25519 AAAAC3...", &pubkey);
// Convert to raw Ed25519 public key
uint8_t ed25519_pk[32];
// ... extract from pubkey ...
// Verify signature
const uint8_t message[] = "Hello, secure world!";
uint8_t signature[64] = {...}; // From signing
ed25519_pk,
message,
sizeof(message) - 1,
signature
);
if (err == ASCIICHAT_OK) {
log_info("Signature is valid!");
} else {
log_error("Signature verification failed");
}
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
asciichat_error_t ed25519_verify_signature(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], const uint8_t *message, size_t message_len, const uint8_t signature[ED25519_SIGNATURE_SIZE], const char *gpg_key_id)
Definition ssh_keys.c:1209

Security Features:

  • Constant-time signature verification (prevents timing attacks)
  • Automatic validation of signature format (must be 64 bytes)
  • Returns error immediately if signature is invalid

Architecture

Module Structure

The key management module is organized into specialized submodules:

Core Modules:

  • keys.h: Unified key parsing interface
  • types.h: Key type definitions and structures
  • validation.h: Key validation and security functions

Format-Specific Modules:

Support Modules:

  • pem.h: PEM encoding/decoding utilities
  • http_client.h: BearSSL HTTPS client for key fetching

Data Structures

Public Key Structure:

typedef struct {
key_type_t type; // KEY_TYPE_ED25519, KEY_TYPE_X25519, or KEY_TYPE_GPG
uint8_t data[32]; // 32-byte public key
char comment[256]; // Optional comment/label
key_type_t
Key type enumeration.
Definition key_types.h:56

Private Key Structure:

typedef struct {
key_type_t type; // KEY_TYPE_ED25519 or KEY_TYPE_X25519
union {
uint8_t x25519[32]; // X25519 private key (32 bytes)
uint8_t ed25519[64]; // Ed25519 private key (seed + public, 64 bytes)
} key;
char comment[256]; // Optional comment/label
bool use_ssh_agent; // Use SSH agent for signing
bool use_gpg_agent; // Use GPG agent for signing (may be disabled)

Usage Examples

Basic Key Loading

#include "crypto/keys/keys.h"
// Load server public key
public_key_t server_pubkey;
"github:server-username",
&server_pubkey
);
if (err != ASCIICHAT_OK) {
log_error("Failed to load server public key");
return err;
}
// Validate key
err = validate_public_key(&server_pubkey);
if (err != ASCIICHAT_OK) {
log_error("Invalid server public key");
return err;
}
// Convert to X25519 for key exchange
uint8_t x25519_pk[32];
err = public_key_to_x25519(&server_pubkey, x25519_pk);

Client Authentication

// Load client private key
private_key_t client_privkey;
asciichat_error_t err = parse_private_key("~/.ssh/id_ed25519", &client_privkey);
// Try to use SSH agent if available
client_privkey.use_ssh_agent = true;
// Sign handshake challenge
uint8_t challenge[] = {...}; // From server
uint8_t signature[64];
&client_privkey,
challenge,
sizeof(challenge),
signature
);
// Send signature to server
send_signature_to_server(signature);

Server Key Whitelist

Loading from file (recommended):

// Server: Load authorized client keys from file
// File can be authorized_keys format or .pub file with multiple entries (one per line)
size_t num_authorized = 0;
asciichat_error_t err = parse_client_keys(
"~/.ssh/authorized_keys", // File with multiple keys, one per line
client_keys,
&num_authorized,
);
// File format (one key per line):
// ssh-ed25519 AAAAC3... alice@example.com
// ssh-ed25519 AAAAC3... bob@example.com
#define MAX_CLIENTS
Maximum possible clients (static array size) - actual runtime limit set by –max-clients (1-128).

Loading from array:

// Server: Load authorized client keys from array
const char *authorized_clients[] = {
"github:alice",
"github:bob",
"ssh-ed25519 AAAAC3... charlie@example.com"
};
size_t num_authorized = 0;
for (size_t i = 0; i < sizeof(authorized_clients) / sizeof(authorized_clients[0]); i++) {
if (parse_public_key(authorized_clients[i], &client_keys[num_authorized]) == ASCIICHAT_OK) {
if (validate_public_key(&client_keys[num_authorized]) == ASCIICHAT_OK) {
num_authorized++;
}
}
}

// Verify incoming client signatures against whitelist bool is_authorized = false; for (size_t i = 0; i < num_authorized; i++) { if (ed25519_verify_signature( client_keys[i].key, // .key field (32 bytes), not .data challenge, sizeof(challenge), signature ) == ASCIICHAT_OK) { is_authorized = true; break; } }

Security Considerations

File Permissions

Private Keys:

  • Should have restrictive permissions (0600 on Unix)
  • Function validates and warns if permissions are too permissive
  • Never share private keys

Public Keys:

  • Can be world-readable (no sensitive data)
  • Still validate format before use

Key Storage

In-Memory Keys:

  • Private keys in memory should be zeroed after use
  • Use sodium_memzero() for secure memory clearing
  • Avoid leaving keys in memory longer than necessary

SSH Agent:

  • More secure: keys stay in agent process (isolated)
  • Private keys never loaded into application memory
  • Recommended for production use

GPG Agent:

  • Similar security benefits to SSH agent
  • Currently may be disabled (check build configuration)

Validation

Always Validate Keys:

  • Check return values from parsing functions
  • Explicitly validate keys before use
  • Reject keys with all-zero data
  • Verify key sizes match expected values

Zero Key Detection:

  • Validation functions reject all-zero keys
  • Zero keys are mathematically invalid
  • Protects against accidentally using uninitialized keys

Limitations and Restrictions

Supported Key Types

Currently Supported:

  • Ed25519 public and private keys (SSH format)
  • X25519 keys (raw hex or base64)
  • GPG Ed25519 keys (may be disabled)

Not Supported:

  • RSA keys (any size)
  • ECDSA keys (any curve)
  • GPG RSA/ECDSA keys
  • Other key formats

Rationale:

  • libsodium only supports Ed25519/X25519
  • Protocol assumes fixed-size keys (32 bytes public, 32/64 bytes private)
  • RSA/ECDSA would require OpenSSL and protocol changes

GPG Support Status

Current Status:

  • GPG key parsing code exists
  • GPG support may be disabled in build configuration
  • GPG agent support exists but may not be enabled

Workaround:

  • Use SSH keys instead of GPG keys
  • SSH keys provide equivalent functionality
  • SSH agent support is fully functional

API Reference

Unified Key Parsing:

asciichat_error_t parse_public_key(const char *input, public_key_t *key_out);

Key Validation:

Key Conversion:

Signing and Verification:

size_t message_len, uint8_t signature[64]);
asciichat_error_t ed25519_verify_signature(const uint8_t public_key[32], const uint8_t *message,
size_t message_len, const uint8_t signature[64]);

HTTPS Key Fetching:

asciichat_error_t fetch_github_ssh_keys(const char *username, char ***keys_out, size_t *num_keys);
asciichat_error_t fetch_gitlab_ssh_keys(const char *username, char ***keys_out, size_t *num_keys);
asciichat_error_t fetch_github_gpg_keys(const char *username, char ***keys_out, size_t *num_keys);
asciichat_error_t fetch_gitlab_gpg_keys(const char *username, char ***keys_out, size_t *num_keys);
See also
crypto/keys/keys.h
crypto/keys/types.h
crypto/keys/validation.h
crypto/keys/ssh_keys.h
crypto/keys/gpg_keys.h
crypto/keys/https_keys.h

Typedef Documentation

◆ crypto_handshake_context_t

typedef struct crypto_handshake_context_t crypto_handshake_context_t

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

Cryptographic handshake context structure.

Manages the complete handshake state for a single connection, including key exchange, authentication, and connection metadata.

Note
Server/Client specific fields:
  • Server-only: server_public_key, server_private_key, client_whitelist
  • Client-only: client_public_key, client_private_key, expected_server_key
Dynamic crypto parameters: All size fields are stored in crypto_ctx and accessed via ctx->crypto_ctx.* (public_key_size, auth_public_key_size, etc.)
Authentication modes:
  • Password: Uses Argon2id-derived key for authentication
  • Client key: Uses Ed25519 signature for client authentication (whitelist)
  • Server identity: Uses Ed25519 signature for server authentication (known_hosts)
State validation: Functions validate current state before proceeding. Invalid state transitions return ERROR_INVALID_STATE.

Enumeration Type Documentation

◆ key_type_t

enum key_type_t

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

Key type enumeration.

Represents the type of cryptographic key being used. All keys are ultimately converted to X25519 for key exchange.

Note
RSA and ECDSA are NOT supported because:
  • libsodium (our crypto library) only supports Ed25519/X25519
  • RSA/ECDSA require variable-length keys and signatures
  • Protocol assumes fixed 128-byte authenticated handshake (ephemeral:32 + identity:32 + sig:64)
  • Adding RSA/ECDSA support would require OpenSSL and protocol changes
Enumerator
KEY_TYPE_UNKNOWN 

Unknown or invalid key type

KEY_TYPE_ED25519 

SSH Ed25519 key (converts to X25519 for key exchange)

KEY_TYPE_X25519 

Native X25519 key (raw hex or base64)

KEY_TYPE_GPG 

GPG key (Ed25519 variant, derived to X25519)

Definition at line 56 of file key_types.h.

56 {
@ KEY_TYPE_UNKNOWN
Definition key_types.h:57
@ KEY_TYPE_ED25519
Definition key_types.h:58
@ KEY_TYPE_GPG
Definition key_types.h:60
@ KEY_TYPE_X25519
Definition key_types.h:59

Function Documentation

◆ build_github_gpg_url()

asciichat_error_t build_github_gpg_url ( const char * username,
char * url_out,
size_t url_size )

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

Construct GitHub GPG keys URL.

Parameters
usernameGitHub username (must not be NULL)
url_outOutput buffer for URL (must not be NULL)
url_sizeSize of URL buffer (must be >= 64)
Returns
ASCIICHAT_OK on success, error code on failure

Constructs GitHub GPG keys URL: https://github.com/username.gpg

Note
URL format: Uses standard GitHub GPG keys endpoint. Format: "https://github.com/{username}.gpg"
Buffer requirements: URL buffer must be at least 64 bytes (same as build_github_ssh_url).
Warning
URL buffer must be large enough for formatted URL.

Definition at line 111 of file https_keys.c.

111 {
112 if (!username || !url_out) {
113 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, url_out=%p", username, url_out);
114 return ERROR_INVALID_PARAM;
115 }
116
117 if (url_size < 64) {
118 SET_ERRNO(ERROR_INVALID_PARAM, "URL buffer too small: %zu (minimum 64)", url_size);
119 return ERROR_INVALID_PARAM;
120 }
121
122 // Strip .gpg suffix if user already included it (e.g., "github:zfogg.gpg")
123 char clean_username[BUFFER_SIZE_SMALL];
124 SAFE_STRNCPY(clean_username, username, sizeof(clean_username) - 1);
125 size_t len = strlen(clean_username);
126 if (len > 4 && strcmp(clean_username + len - 4, ".gpg") == 0) {
127 clean_username[len - 4] = '\0'; // Remove .gpg suffix
128 }
129
130 // Construct GitHub GPG keys URL: https://github.com/username.gpg
131 int result = safe_snprintf(url_out, url_size, "https://github.com/%s.gpg", clean_username);
132 if (result < 0 || result >= (int)url_size) {
133 SET_ERRNO(ERROR_STRING, "Failed to construct GitHub GPG URL");
134 return ERROR_STRING;
135 }
136
137 return ASCIICHAT_OK;
138}
#define SET_ERRNO(code,...)
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
#define SAFE_STRNCPY(dst, src, size)
@ ERROR_STRING
@ ERROR_INVALID_PARAM

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, ERROR_STRING, SAFE_STRNCPY, and SET_ERRNO.

Referenced by fetch_github_gpg_keys().

◆ build_github_ssh_url()

asciichat_error_t build_github_ssh_url ( const char * username,
char * url_out,
size_t url_size )

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

Construct GitHub SSH keys URL.

Parameters
usernameGitHub username (must not be NULL)
url_outOutput buffer for URL (must not be NULL)
url_sizeSize of URL buffer (must be >= 64)
Returns
ASCIICHAT_OK on success, error code on failure

Constructs GitHub SSH keys URL: https://github.com/username.keys

Note
URL format: Uses standard GitHub SSH keys endpoint. Format: "https://github.com/{username}.keys"
Buffer requirements: URL buffer must be at least 64 bytes. Format: "https://github.com/" (19 chars) + username + ".keys" (6 chars) = 25 + username length
Warning
URL buffer must be large enough for formatted URL. Function validates buffer size but may overflow if buffer is too small.

Definition at line 69 of file https_keys.c.

69 {
70 if (!username || !url_out) {
71 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, url_out=%p", username, url_out);
73 }
74
75 if (url_size < 64) {
76 SET_ERRNO(ERROR_INVALID_PARAM, "URL buffer too small: %zu (minimum 64)", url_size);
78 }
79
80 // Construct GitHub SSH keys URL: https://github.com/username.keys
81 int result = safe_snprintf(url_out, url_size, "https://github.com/%s.keys", username);
82 if (result < 0 || result >= (int)url_size) {
83 SET_ERRNO(ERROR_STRING, "Failed to construct GitHub SSH URL");
84 return ERROR_STRING;
85 }
86
87 return ASCIICHAT_OK;
88}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_STRING, and SET_ERRNO.

Referenced by fetch_github_ssh_keys().

◆ build_gitlab_gpg_url()

asciichat_error_t build_gitlab_gpg_url ( const char * username,
char * url_out,
size_t url_size )

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

Construct GitLab GPG keys URL.

Parameters
usernameGitLab username (must not be NULL)
url_outOutput buffer for URL (must not be NULL)
url_sizeSize of URL buffer (must be >= 64)
Returns
ASCIICHAT_OK on success, error code on failure

Constructs GitLab GPG keys URL: https://gitlab.com/username.gpg

Note
URL format: Uses standard GitLab GPG keys endpoint. Format: "https://gitlab.com/{username}.gpg"
Buffer requirements: URL buffer must be at least 64 bytes (same as build_gitlab_ssh_url).
Warning
URL buffer must be large enough for formatted URL.

Definition at line 140 of file https_keys.c.

140 {
141 if (!username || !url_out) {
142 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, url_out=%p", username, url_out);
143 return ERROR_INVALID_PARAM;
144 }
145
146 if (url_size < 64) {
147 SET_ERRNO(ERROR_INVALID_PARAM, "URL buffer too small: %zu (minimum 64)", url_size);
148 return ERROR_INVALID_PARAM;
149 }
150
151 // Strip .gpg suffix if user already included it (e.g., "gitlab:zfogg.gpg")
152 char clean_username[BUFFER_SIZE_SMALL];
153 SAFE_STRNCPY(clean_username, username, sizeof(clean_username) - 1);
154 size_t len = strlen(clean_username);
155 if (len > 4 && strcmp(clean_username + len - 4, ".gpg") == 0) {
156 clean_username[len - 4] = '\0'; // Remove .gpg suffix
157 }
158
159 // Construct GitLab GPG keys URL: https://gitlab.com/username.gpg
160 int result = safe_snprintf(url_out, url_size, "https://gitlab.com/%s.gpg", clean_username);
161 if (result < 0 || result >= (int)url_size) {
162 SET_ERRNO(ERROR_STRING, "Failed to construct GitLab GPG URL");
163 return ERROR_STRING;
164 }
165
166 return ASCIICHAT_OK;
167}

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, ERROR_INVALID_PARAM, ERROR_STRING, SAFE_STRNCPY, and SET_ERRNO.

Referenced by fetch_gitlab_gpg_keys().

◆ build_gitlab_ssh_url()

asciichat_error_t build_gitlab_ssh_url ( const char * username,
char * url_out,
size_t url_size )

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

Construct GitLab SSH keys URL.

Parameters
usernameGitLab username (must not be NULL)
url_outOutput buffer for URL (must not be NULL)
url_sizeSize of URL buffer (must be >= 64)
Returns
ASCIICHAT_OK on success, error code on failure

Constructs GitLab SSH keys URL: https://gitlab.com/username.keys

Note
URL format: Uses standard GitLab SSH keys endpoint. Format: "https://gitlab.com/{username}.keys"
Buffer requirements: URL buffer must be at least 64 bytes (same as build_github_ssh_url).
Warning
URL buffer must be large enough for formatted URL.

Definition at line 90 of file https_keys.c.

90 {
91 if (!username || !url_out) {
92 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, url_out=%p", username, url_out);
94 }
95
96 if (url_size < 64) {
97 SET_ERRNO(ERROR_INVALID_PARAM, "URL buffer too small: %zu (minimum 64)", url_size);
99 }
100
101 // Construct GitLab SSH keys URL: https://gitlab.com/username.keys
102 int result = safe_snprintf(url_out, url_size, "https://gitlab.com/%s.keys", username);
103 if (result < 0 || result >= (int)url_size) {
104 SET_ERRNO(ERROR_STRING, "Failed to construct GitLab SSH URL");
105 return ERROR_STRING;
106 }
107
108 return ASCIICHAT_OK;
109}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_STRING, and SET_ERRNO.

Referenced by fetch_gitlab_ssh_keys().

◆ check_gpg_key_expiry()

asciichat_error_t check_gpg_key_expiry ( const char * gpg_key_text,
bool * is_expired )

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

Check if GPG key is expired.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
is_expiredOutput: true if key is expired, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Checks if GPG key has expired by parsing expiration date from key structure.

Note
Expiration checking: Parses OpenPGP packet structure to find expiration date. Compares expiration date with current date.
Default behavior: Currently defaults to not expired if parsing fails. Function returns error but sets is_expired to false.
Warning
NOT YET IMPLEMENTED: This function is not yet implemented. Returns ERROR_CRYPTO_KEY with "GPG key expiry checking not yet implemented". Defaults is_expired to false before returning error.
GPG support is currently disabled. Function will not work until implemented.

Definition at line 184 of file gpg_keys.c.

184 {
185 if (!gpg_key_text || !is_expired) {
186 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, is_expired=%p", gpg_key_text, is_expired);
187 return ERROR_INVALID_PARAM;
188 }
189
190 // For GPG key expiry checking, we need a key ID
191 // If gpg_key_text is a key ID (8, 16, or 40 hex chars), use it directly
192 // Otherwise, we'd need to parse the GPG armored text (complex)
193 size_t key_len = strlen(gpg_key_text);
194 const char *key_id = gpg_key_text;
195
196 // Check if it looks like a key ID (hex characters only)
197 bool is_hex = true;
198 for (size_t i = 0; i < key_len; i++) {
199 if (!((gpg_key_text[i] >= '0' && gpg_key_text[i] <= '9') || (gpg_key_text[i] >= 'A' && gpg_key_text[i] <= 'F') || (gpg_key_text[i] >= 'a' && gpg_key_text[i] <= 'f'))) {
200 is_hex = false;
201 break;
202 }
203 }
204
205 // Only support key ID format (8, 16, or 40 hex chars)
206 if (!is_hex || (key_len != 8 && key_len != 16 && key_len != 40)) {
207 log_warn("Input is not a key ID format (expected 8/16/40 hex chars)");
208 *is_expired = false; // Assume not expired if we can't check
209 return ASCIICHAT_OK;
210 }
211
212 // Use gpg --list-keys with colon-separated output to check expiry
213 char cmd[BUFFER_SIZE_MEDIUM];
214 safe_snprintf(cmd, sizeof(cmd), "gpg --list-keys --with-colons %s " PLATFORM_SHELL_NULL_REDIRECT, key_id);
215
216 FILE *fp = NULL;
217 if (platform_popen("gpg_keys", cmd, "r", &fp) != ASCIICHAT_OK || !fp) {
218 log_error("Failed to run gpg --list-keys for key %s", key_id);
219 *is_expired = false; // Assume not expired if we can't check
220 return ASCIICHAT_OK;
221 }
222
223 char line[BUFFER_SIZE_LARGE];
224 bool found_pub = false;
225 *is_expired = false;
226
227 // Parse colon-separated output
228 // Format: pub:trust:keylen:algo:keyid:creation:expiry:...
229 // Field 6 is expiry timestamp (seconds since epoch), or empty if no expiry
230 while (fgets(line, sizeof(line), fp)) {
231 if (strncmp(line, "pub:", 4) == 0) {
232 found_pub = true;
233
234 // Split line by colons
235 char *fields[GPG_COLON_FIELD_CAPACITY];
236 int field_count = 0;
237 char *ptr = line;
238 char *field_start = ptr;
239
240 while (*ptr && field_count < GPG_COLON_FIELD_CAPACITY) {
241 if (*ptr == ':' || *ptr == '\n') {
242 *ptr = '\0';
243 fields[field_count++] = field_start;
244 field_start = ptr + 1;
245 }
246 ptr++;
247 }
248
249 // Field 6 is expiry date (index 6)
250 if (field_count >= 7 && strlen(fields[6]) > 0) {
251 // Parse expiry timestamp
252 long expiry_timestamp = strtol(fields[6], NULL, 10);
253 time_t now = time(NULL);
254
255 if (expiry_timestamp > 0 && expiry_timestamp <= now) {
256 *is_expired = true;
257 log_warn("GPG key %s has expired (expiry: %ld, now: %ld)", key_id, expiry_timestamp, (long)now);
258 } else if (expiry_timestamp > 0) {
259 log_debug("GPG key %s expires at timestamp %ld (valid)", key_id, expiry_timestamp);
260 } else {
261 log_debug("GPG key %s has no expiration date", key_id);
262 }
263 } else {
264 log_debug("GPG key %s has no expiration date (field empty)", key_id);
265 }
266
267 break; // Found the pub line, stop parsing
268 }
269 }
270
271 platform_pclose(&fp);
272
273 if (!found_pub) {
274 log_warn("Could not find GPG key %s in keyring", key_id);
275 *is_expired = false; // Assume not expired if key not found
276 }
277
278 return ASCIICHAT_OK;
279}
#define GPG_COLON_FIELD_CAPACITY
Definition gpg_keys.c:11
#define BUFFER_SIZE_LARGE
Large buffer size (1024 bytes).
#define BUFFER_SIZE_MEDIUM
Medium buffer size (512 bytes).
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
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, ERROR_INVALID_PARAM, GPG_COLON_FIELD_CAPACITY, log_debug, log_error, log_warn, platform_pclose(), platform_popen(), and SET_ERRNO.

◆ check_key_expiry()

asciichat_error_t check_key_expiry ( const public_key_t * key,
bool * is_expired )

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

Check if a key is expired.

Parameters
keyKey to check (must not be NULL)
is_expiredOutput: true if expired, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Checks if key has expired by parsing expiration date from key structure.

Note
Expiration checking: Would parse key creation dates and expiration times from key structure. Currently not implemented.
Current implementation: Always returns false (not expired). Key expiry checking is not yet implemented.
Warning
NOT YET IMPLEMENTED: This function always returns false (not expired). Key expiry checking is not yet implemented.

Definition at line 118 of file keys_validation.c.

118 {
119 if (!key || !is_expired) {
120 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, is_expired=%p", key, is_expired);
121 return ERROR_INVALID_PARAM;
122 }
123
124 // For now, we don't implement key expiry checking
125 // This would require parsing key creation dates and expiration times
126 *is_expired = false;
127
128 return ASCIICHAT_OK;
129}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ check_key_fingerprint()

asciichat_error_t check_key_fingerprint ( const public_key_t * key,
const uint8_t * fingerprint,
size_t fingerprint_len,
bool * matches )

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

Check if key matches a fingerprint.

Parameters
keyKey to check (must not be NULL)
fingerprintFingerprint to match against (must not be NULL)
fingerprint_lenLength of fingerprint (must be > 0)
matchesOutput: true if fingerprint matches, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Checks if key matches a fingerprint by computing key fingerprint and comparing.

Note
Fingerprint comparison: Computes key fingerprint using generate_key_fingerprint() and compares with provided fingerprint using constant-time comparison.
Constant-time: Uses constant-time comparison to prevent timing attacks.
Fingerprint format: Fingerprint is typically SHA-256 hash of key material. Length depends on hash algorithm used (typically 32 bytes for SHA-256).
Warning
Always uses constant-time comparison for fingerprints. Do NOT use regular memcmp() for fingerprint comparison.

Definition at line 419 of file keys_validation.c.

419 {
420 if (!key || !fingerprint || !matches) {
421 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, fingerprint=%p, matches=%p", key, fingerprint, matches);
422 return ERROR_INVALID_PARAM;
423 }
424
425 *matches = false;
426
427 // Generate fingerprint for the key
428 uint8_t key_fingerprint[crypto_hash_sha256_BYTES];
429 asciichat_error_t fingerprint_result = generate_key_fingerprint(key, key_fingerprint, 32);
430 if (fingerprint_result != ASCIICHAT_OK) {
431 return fingerprint_result;
432 }
433
434 // Compare fingerprints
435 size_t compare_len = (fingerprint_len < 32) ? fingerprint_len : 32;
436 if (sodium_memcmp(key_fingerprint, fingerprint, compare_len) == 0) {
437 *matches = true;
438 }
439
440 return ASCIICHAT_OK;
441}
asciichat_error_t generate_key_fingerprint(const public_key_t *key, uint8_t *fingerprint_out, size_t fingerprint_size)
Generate key fingerprint.

References ASCIICHAT_OK, ERROR_INVALID_PARAM, generate_key_fingerprint(), and SET_ERRNO.

◆ check_key_patterns()

asciichat_error_t check_key_patterns ( const public_key_t * key,
bool * has_weak_patterns )

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

Check for key reuse or weak patterns.

Parameters
keyKey to check (must not be NULL)
has_weak_patternsOutput: true if weak patterns found, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Checks key for weak patterns that could indicate security vulnerabilities. Detects keys with predictable or weak patterns.

Note
Pattern analysis: Would analyze key material for weak patterns. Currently not fully implemented.
Weak patterns: Would detect:
  • Keys with repeated patterns
  • Keys with low entropy
  • Keys matching known weak patterns
Warning
NOT YET FULLY IMPLEMENTED: Weak pattern detection is not yet fully implemented. Function may always return false (no weak patterns).

Definition at line 305 of file keys_validation.c.

305 {
306 if (!key || !has_weak_patterns) {
307 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, has_weak_patterns=%p", key, has_weak_patterns);
308 return ERROR_INVALID_PARAM;
309 }
310
311 *has_weak_patterns = false;
312
313 // Check for sequential patterns
314 bool is_sequential = true;
315 for (int i = 1; i < 32; i++) {
316 if (key->key[i] != key->key[i - 1] + 1) {
317 is_sequential = false;
318 break;
319 }
320 }
321
322 if (is_sequential) {
323 *has_weak_patterns = true;
324 return ASCIICHAT_OK;
325 }
326
327 // Check for repeated byte patterns (e.g., all 0xAA, all 0x55)
328 // Common weak patterns to check
329 const uint8_t weak_bytes[] = {0x00, 0xFF, 0xAA, 0x55, 0x11, 0x22, 0x33, 0x44, 0x66, 0x77, 0x88, 0x99, 0xBB, 0xCC, 0xDD, 0xEE};
330 for (size_t pattern_idx = 0; pattern_idx < sizeof(weak_bytes); pattern_idx++) {
331 uint8_t pattern_byte = weak_bytes[pattern_idx];
332 bool is_repeated = true;
333 for (size_t j = 0; j < 32; j++) {
334 // CORRECT: Compare against pattern_byte, not key->key[0]
335 if (key->key[j] != pattern_byte) {
336 is_repeated = false;
337 break;
338 }
339 }
340 if (is_repeated) {
341 *has_weak_patterns = true;
342 return ASCIICHAT_OK;
343 }
344 }
345
346 // Check for alternating bit patterns (e.g., 0xAA 0xBB 0xAA 0xBB or 0x55 0xAA 0x55 0xAA)
347 // A proper alternating pattern has at most 2 unique byte values that truly alternate
348 bool byte_appeared[256] = {0};
349 int unique_values = 0;
350 for (size_t i = 0; i < 32; i++) {
351 if (!byte_appeared[key->key[i]]) {
352 byte_appeared[key->key[i]] = true;
353 unique_values++;
354 }
355 }
356
357 // Only consider it weak if there are 2 or fewer unique values AND they properly alternate
358 if (unique_values <= 2) {
359 bool is_alternating = true;
360 for (size_t i = 1; i < 32; i++) {
361 // In a true alternating pattern:
362 // 1. Adjacent bytes must be different
363 // 2. Pattern must repeat every 2 bytes (byte[i] == byte[i-2])
364 if (key->key[i] == key->key[i - 1] || (i >= 2 && key->key[i] != key->key[i - 2])) {
365 is_alternating = false;
366 break;
367 }
368 }
369 if (is_alternating) {
370 *has_weak_patterns = true;
371 return ASCIICHAT_OK;
372 }
373 }
374
375 // Check for common cryptographic initialization patterns
376 // OpenSSL weak keys, old Debian SSH keys, etc.
377 uint32_t *words = (uint32_t *)key->key;
378 // Check if all 32-bit words are identical
379 bool all_words_same = true;
380 for (size_t i = 1; i < 8; i++) {
381 if (words[i] != words[0]) {
382 all_words_same = false;
383 break;
384 }
385 }
386 if (all_words_same) {
387 *has_weak_patterns = true;
388 return ASCIICHAT_OK;
389 }
390
391 return ASCIICHAT_OK;
392}
unsigned int uint32_t
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:78

References ASCIICHAT_OK, ERROR_INVALID_PARAM, public_key_t::key, and SET_ERRNO.

◆ check_key_strength()

asciichat_error_t check_key_strength ( const public_key_t * key,
bool * is_weak )

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

Check if key has weak parameters.

Parameters
keyKey to check (must not be NULL)
is_weakOutput: true if weak, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Checks if key has weak cryptographic parameters. Detects keys with weak entropy or predictable patterns.

Note
Weak key detection: Would analyze key material for weak patterns. Currently not fully implemented.
Security analysis: Would check for:
  • Low entropy keys
  • Predictable patterns
  • Known weak keys
Warning
NOT YET FULLY IMPLEMENTED: Weak key detection is not yet fully implemented. Function may always return false (not weak).

Definition at line 255 of file keys_validation.c.

255 {
256 if (!key || !is_weak) {
257 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, is_weak=%p", key, is_weak);
258 return ERROR_INVALID_PARAM;
259 }
260
261 *is_weak = false;
262
263 // Check for all zeros (already checked in validate_public_key)
264 // Check for all ones
265 bool is_ones = true;
266 for (int i = 0; i < 32; i++) {
267 if (key->key[i] != 0xFF) {
268 is_ones = false;
269 break;
270 }
271 }
272
273 if (is_ones) {
274 *is_weak = true;
275 return ASCIICHAT_OK;
276 }
277
278 // Check for low entropy: Count unique bytes
279 // A properly random 32-byte key should have ~24-32 unique values
280 // Low entropy keys will have very few unique bytes
281 bool byte_seen[256] = {0};
282 int unique_bytes = 0;
283 for (int i = 0; i < 32; i++) {
284 uint8_t byte_val = key->key[i];
285 if (!byte_seen[byte_val]) {
286 byte_seen[byte_val] = true;
287 unique_bytes++;
288 }
289 }
290
291 // If less than 8 unique bytes in 32 bytes, entropy is very low
292 // This indicates non-random key generation (e.g., PRNG seed not properly initialized)
293 if (unique_bytes < 8) {
294 *is_weak = true;
295 return ASCIICHAT_OK;
296 }
297
298 // Additional weak key pattern detection:
299 // - Check for repeated patterns (handled in check_key_patterns)
300 // - Check for known weak sequences (see check_key_patterns)
301
302 return ASCIICHAT_OK;
303}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, public_key_t::key, and SET_ERRNO.

◆ compare_public_keys()

asciichat_error_t compare_public_keys ( const public_key_t * key1,
const public_key_t * key2,
bool * are_equal )

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

Compare two public keys for equality.

Parameters
key1First key to compare (must not be NULL)
key2Second key to compare (must not be NULL)
are_equalOutput: true if keys are equal, false otherwise (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Compares two public keys for equality using constant-time comparison. Compares key type and key data.

Note
Key comparison: Compares key type and 32-byte key data. Uses constant-time comparison to prevent timing attacks.
Constant-time: Uses sodium_memcmp() for constant-time comparison. Prevents timing attacks that could leak key information.
Comment comparison: Comments are NOT compared. Only key type and key data are compared.
Warning
Always uses constant-time comparison for keys. Do NOT use regular memcmp() for key comparison.

Definition at line 398 of file keys_validation.c.

398 {
399 if (!key1 || !key2 || !are_equal) {
400 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key1=%p, key2=%p, are_equal=%p", key1, key2, are_equal);
401 return ERROR_INVALID_PARAM;
402 }
403
404 *are_equal = false;
405
406 // Compare key types
407 if (key1->type != key2->type) {
408 return ASCIICHAT_OK;
409 }
410
411 // Compare key data using constant-time comparison
412 if (sodium_memcmp(key1->key, key2->key, 32) == 0) {
413 *are_equal = true;
414 }
415
416 return ASCIICHAT_OK;
417}
key_type_t type
Definition key_types.h:77

References ASCIICHAT_OK, ERROR_INVALID_PARAM, public_key_t::key, SET_ERRNO, and public_key_t::type.

◆ ed25519_sign_message()

asciichat_error_t ed25519_sign_message ( const private_key_t * key,
const uint8_t * message,
size_t message_len,
uint8_t signature[64] )

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

Sign a message with Ed25519 (uses SSH agent if available, otherwise in-memory key).

Sign a message with Ed25519 private key.

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

Signs a message using Ed25519. This is the main signing function that abstracts SSH agent vs in-memory signing.

Note
Agent support: If use_ssh_agent is true, uses SSH agent for signing. Key stays in agent (not loaded into memory). Signing happens via agent protocol.
In-memory signing: If use_ssh_agent is false, uses in-memory key for signing. Key must be loaded into memory (via parse_private_key()).

Setting use_gpg_agent=true will not work until GPG support is re-enabled.

Note
Signature format: Ed25519 signature is always 64 bytes (R || S format).
Warning
Agent availability: If use_ssh_agent is true but SSH agent is not available, function returns error. Check SSH agent availability before using.

exists but will not work until GPG support is re-enabled.

Parameters
keyEd25519 private key (must not be NULL)
messageMessage to sign (must not be NULL)
message_lenLength of message to sign
signatureOutput buffer for Ed25519 signature (64 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Signs a message using Ed25519. Uses SSH agent if available, otherwise in-memory key.

Note
Agent support: If use_ssh_agent is true, uses SSH agent for signing. Key stays in agent (not loaded into memory). Signing happens via agent protocol.
In-memory signing: If use_ssh_agent is false, uses in-memory key for signing. Key must be loaded into memory (via parse_ssh_private_key()).
Signature format: Ed25519 signature is always 64 bytes (R || S format).
Warning
Agent availability: If use_ssh_agent is true but SSH agent is not available, function returns error. Check SSH agent availability before using.

References ED25519_SIGNATURE_SIZE.

◆ ed25519_to_x25519_private()

asciichat_error_t ed25519_to_x25519_private ( const uint8_t ed25519_sk[64],
uint8_t x25519_sk[32] )

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

Convert Ed25519 private key to X25519 for key exchange.

Parameters
ed25519_skEd25519 private key (64 bytes: seed + public, must not be NULL)
x25519_skOutput buffer for X25519 private key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Converts Ed25519 private key to X25519 format for Diffie-Hellman key exchange. Uses libsodium's conversion function.

Note
Ed25519 key format: Ed25519 private key is 64 bytes (32-byte seed + 32-byte public key). Function extracts seed (first 32 bytes) and converts to X25519 scalar.
Conversion: Uses crypto_sign_ed25519_sk_to_curve25519() from libsodium. Conversion is mathematically safe (same curve, different representation).
Key size: Ed25519 private key is 64 bytes, X25519 private key is 32 bytes. Extracts 32-byte seed from Ed25519 key and converts to X25519 scalar.
Use case: Used for key exchange when Ed25519 key is used for signing but X25519 is needed for key exchange (DH).
Warning
Ed25519 key must be exactly 64 bytes (32-byte seed + 32-byte public). Function validates key size before conversion.

References ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, ED25519_SIGNATURE_SIZE, and X25519_KEY_SIZE.

◆ ed25519_to_x25519_public()

asciichat_error_t ed25519_to_x25519_public ( const uint8_t ed25519_pk[32],
uint8_t x25519_pk[32] )

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

Convert Ed25519 public key to X25519 for key exchange.

Parameters
ed25519_pkEd25519 public key (32 bytes, must not be NULL)
x25519_pkOutput buffer for X25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Converts Ed25519 public key to X25519 format for Diffie-Hellman key exchange. Uses libsodium's conversion function.

Note
Conversion: Uses crypto_sign_ed25519_pk_to_curve25519() from libsodium. Conversion is mathematically safe (same curve, different representation).
Key size: Both Ed25519 and X25519 keys are 32 bytes. No size change during conversion.
Use case: Used for key exchange when Ed25519 key is used for signing but X25519 is needed for key exchange (DH).
Warning
All keys must be 32 bytes. Function validates key size before conversion.

References ED25519_PUBLIC_KEY_SIZE, and X25519_KEY_SIZE.

◆ ed25519_verify_signature()

asciichat_error_t ed25519_verify_signature ( const uint8_t public_key[32],
const uint8_t * message,
size_t message_len,
const uint8_t signature[64],
const char * gpg_key_id )

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

Verify an Ed25519 signature.

Parameters
public_keyEd25519 public key (32 bytes)
messageMessage that was signed (must not be NULL)
message_lenLength of message that was signed
signatureEd25519 signature to verify (64 bytes)
Returns
ASCIICHAT_OK if signature is valid, error code on failure

Verifies an Ed25519 signature using libsodium's verification function.

Note
Signature format: Ed25519 signature is always 64 bytes (R || S format).
Verification: Uses crypto_sign_ed25519_verify_detached() from libsodium. Returns error if signature is invalid or message was tampered with.
Constant-time: Verification uses constant-time comparison to prevent timing attacks.
Warning
Always check return value. Error indicates invalid signature or tampering.
Parameters
public_keyEd25519 public key (32 bytes, must not be NULL)
messageMessage that was signed (must not be NULL)
message_lenLength of message that was signed
signatureEd25519 signature to verify (64 bytes, must not be NULL)
Returns
ASCIICHAT_OK if signature is valid, error code on failure

Verifies an Ed25519 signature using libsodium's verification function.

Note
Signature format: Ed25519 signature is always 64 bytes (R || S format).
Verification: Uses crypto_sign_ed25519_verify_detached() from libsodium. Returns error if signature is invalid or message was tampered with.
Constant-time: Verification uses constant-time comparison to prevent timing attacks.
Warning
Always check return value. Error indicates invalid signature or tampering.

References ED25519_PUBLIC_KEY_SIZE, and ED25519_SIGNATURE_SIZE.

◆ extract_ed25519_from_gpg()

asciichat_error_t extract_ed25519_from_gpg ( const char * gpg_key_text,
uint8_t ed25519_pk[32] )

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

Extract Ed25519 public key from GPG key.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
ed25519_pkOutput buffer for Ed25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts Ed25519 public key from GPG key by parsing OpenPGP packet structure.

Note
OpenPGP parsing: Parses OpenPGP packet structure to find Ed25519 public key packet. Requires parsing of packet headers and packet data.
Key extraction: Finds Ed25519 subkey in GPG key structure. Extracts 32-byte Ed25519 public key material.
Warning
NOT YET IMPLEMENTED: This function is not yet implemented. Returns ERROR_CRYPTO_KEY with "Ed25519 extraction from GPG key not yet implemented".
GPG support is currently disabled. Function will not work until implemented.

Definition at line 116 of file gpg_keys.c.

116 {
117 if (!gpg_key_id || !ed25519_pk) {
118 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_id=%p, ed25519_pk=%p", gpg_key_id, ed25519_pk);
119 return ERROR_INVALID_PARAM;
120 }
121
122 // Use gpg_get_public_key() to extract Ed25519 public key from GPG keyring
123 // Note: gpg_key_id should be the key ID (e.g., "7FE90A79F2E80ED3")
124 char keygrip[MAX_GPG_KEYGRIP_LEN];
125 if (gpg_get_public_key(gpg_key_id, ed25519_pk, keygrip) != 0) {
126 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to extract Ed25519 public key from GPG for key ID: %s", gpg_key_id);
127 }
128
129 return ASCIICHAT_OK;
130}
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.
Definition export.c:247
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
#define MAX_GPG_KEYGRIP_LEN
Definition sizes.h:177

References ASCIICHAT_OK, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, gpg_get_public_key(), MAX_GPG_KEYGRIP_LEN, and SET_ERRNO.

Referenced by gpg_to_x25519_public(), and parse_gpg_key().

◆ extract_gpg_key_comment()

asciichat_error_t extract_gpg_key_comment ( const char * gpg_key_text,
char * comment_out,
size_t comment_size )

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

Extract key comment/email from GPG key.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
comment_outOutput buffer for comment (must not be NULL)
comment_sizeSize of comment buffer (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts comment/email from GPG key by parsing user ID packet.

Note
Comment extraction: Parses OpenPGP packet structure to find user ID packet. Extracts comment/email from user ID packet.
User ID format: GPG user IDs typically contain name and email. Format: "Name <email@example.com>" or just "email@example.com"
Warning
GPG support is currently disabled. Function may not work until GPG support is re-enabled.

Definition at line 322 of file gpg_keys.c.

322 {
323 if (!gpg_key_text || !comment_out) {
324 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, comment_out=%p", gpg_key_text, comment_out);
325 return ERROR_INVALID_PARAM;
326 }
327
328 if (comment_size == 0) {
329 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid comment size: %zu", comment_size);
330 return ERROR_INVALID_PARAM;
331 }
332
333 // TODO: Implement GPG key comment extraction
334 // This requires parsing the OpenPGP packet structure and extracting user ID packets
335
336 // For now, use a generic comment
337 SAFE_STRNCPY(comment_out, "GPG key", comment_size - 1);
338 return ASCIICHAT_OK;
339}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, SAFE_STRNCPY, and SET_ERRNO.

◆ fetch_github_gpg_keys()

asciichat_error_t fetch_github_gpg_keys ( const char * username,
char *** keys_out,
size_t * num_keys )

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

Fetch GPG keys from GitHub using HTTPS.

Fetch GPG keys from GitHub using BearSSL.

Parameters
usernameGitHub username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitHub: GET https://github.com/username.gpg

Note
Network operation: Requires network connectivity and valid GitHub username. May fail if network is unavailable or username doesn't exist.
GPG format: Fetches GPG keys in armored format. Response contains GPG key blocks (--—BEGIN PGP PUBLIC KEY BLOCK--—).
Memory management: Caller must free each key string and the keys array (same as fetch_github_ssh_keys).
Warning
Network dependency: Requires active network connection.
GPG support: GPG key parsing may not work until GPG support is re-enabled.
Parameters
usernameGitHub username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of GPG keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitHub: GET https://github.com/username.gpg

Note
Memory management: Caller must free each key string and the keys array (same as fetch_github_keys).
Warning
Network dependency: Requires active network connection.

Fetch GPG keys from GitHub using HTTPS.

Parameters
usernameGitHub username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of GPG keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitHub: GET https://github.com/username.gpg

Note
Memory management: Caller must free each key string and the keys array (same as fetch_github_keys).
Warning
Network dependency: Requires active network connection.

Definition at line 233 of file https_keys.c.

233 {
234 if (!username || !keys_out || !num_keys) {
235 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, keys_out=%p, num_keys=%p", username, keys_out, num_keys);
236 return ERROR_INVALID_PARAM;
237 }
238
239 // Build the GitHub GPG keys URL
240 char url[BUFFER_SIZE_SMALL];
241 asciichat_error_t url_result = build_github_gpg_url(username, url, sizeof(url));
242 if (url_result != ASCIICHAT_OK) {
243 return url_result;
244 }
245
246 // Fetch the keys using HTTPS
247 char *response_text = NULL;
248 size_t response_len = 0;
249 asciichat_error_t fetch_result = https_fetch_keys(url, &response_text, &response_len);
250 if (fetch_result != ASCIICHAT_OK) {
251 return fetch_result;
252 }
253
254 // Parse GPG keys from the response
255 asciichat_error_t parse_result = parse_gpg_keys_from_response(response_text, response_len, keys_out, num_keys, MAX_CLIENTS);
256
257 // Clean up response text
258 SAFE_FREE(response_text);
259
260 return parse_result;
261}
#define SAFE_FREE(ptr)
asciichat_error_t build_github_gpg_url(const char *username, char *url_out, size_t url_size)
Construct GitHub GPG keys URL.
Definition https_keys.c:111
asciichat_error_t parse_gpg_keys_from_response(const char *response_text, size_t response_len, char ***keys_out, size_t *num_keys, size_t max_keys)
Parse GPG keys from HTTPS response text.
Definition https_keys.c:390

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, build_github_gpg_url(), ERROR_INVALID_PARAM, MAX_CLIENTS, parse_gpg_keys_from_response(), SAFE_FREE, and SET_ERRNO.

Referenced by fetch_github_keys(), and parse_public_keys().

◆ fetch_github_keys()

asciichat_error_t fetch_github_keys ( const char * username,
char *** keys_out,
size_t * num_keys,
bool use_gpg )

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

Fetch SSH/GPG keys from GitHub using BearSSL.

Parameters
usernameGitHub username (must not be NULL)
keys_outOutput array of key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
use_gpgTrue to fetch GPG keys, false to fetch SSH keys
Returns
ASCIICHAT_OK on success, error code on failure

Fetches keys from GitHub:

Note
Network operation: Requires network connectivity and valid GitHub username. May fail if network is unavailable or username doesn't exist.
Memory management: Caller must free each key string and the keys array: c for (size_t i = 0; i < num_keys; i++) { free(keys_out[i]); } free(keys_out);
Warning
Network dependency: Requires active network connection. May fail if GitHub is unreachable or username doesn't exist.

Definition at line 571 of file keys.c.

571 {
572 if (!username || !keys_out || !num_keys) {
573 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
574 }
575
576 if (use_gpg) {
577 return fetch_github_gpg_keys(username, keys_out, num_keys);
578 } else {
579 return fetch_github_ssh_keys(username, keys_out, num_keys);
580 }
581}

References ERROR_INVALID_PARAM, fetch_github_gpg_keys(), fetch_github_ssh_keys(), and SET_ERRNO.

◆ fetch_github_ssh_keys()

asciichat_error_t fetch_github_ssh_keys ( const char * username,
char *** keys_out,
size_t * num_keys )

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

Fetch SSH keys from GitHub using HTTPS.

Parameters
usernameGitHub username (must not be NULL)
keys_outOutput array of SSH key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches SSH keys from GitHub: GET https://github.com/username.keys

Note
Network operation: Requires network connectivity and valid GitHub username. May fail if network is unavailable or username doesn't exist.
Key format: Only Ed25519 SSH keys are parsed from response. Other key types (RSA, ECDSA) are skipped.
Memory management: Caller must free each key string and the keys array: c for (size_t i = 0; i < num_keys; i++) { free(keys_out[i]); } free(keys_out);
Response parsing: Parses response as one key per line. Each line is parsed as SSH key format ("ssh-ed25519 AAAAC3... comment").
Warning
Network dependency: Requires active network connection. May fail if GitHub is unreachable or username doesn't exist.
Memory leak: Caller must free returned strings and array. Function allocates memory that must be freed.

Definition at line 173 of file https_keys.c.

173 {
174 if (!username || !keys_out || !num_keys) {
175 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, keys_out=%p, num_keys=%p", username, keys_out, num_keys);
176 return ERROR_INVALID_PARAM;
177 }
178
179 // Build the GitHub SSH keys URL
180 char url[BUFFER_SIZE_SMALL];
181 asciichat_error_t url_result = build_github_ssh_url(username, url, sizeof(url));
182 if (url_result != ASCIICHAT_OK) {
183 return url_result;
184 }
185
186 // Fetch the keys using HTTPS
187 char *response_text = NULL;
188 size_t response_len = 0;
189 asciichat_error_t fetch_result = https_fetch_keys(url, &response_text, &response_len);
190 if (fetch_result != ASCIICHAT_OK) {
191 return fetch_result;
192 }
193
194 // Parse SSH keys from the response
195 asciichat_error_t parse_result = parse_ssh_keys_from_response(response_text, response_len, keys_out, num_keys, MAX_CLIENTS);
196
197 // Clean up response text
198 SAFE_FREE(response_text);
199
200 return parse_result;
201}
asciichat_error_t build_github_ssh_url(const char *username, char *url_out, size_t url_size)
Construct GitHub SSH keys URL.
Definition https_keys.c:69
asciichat_error_t parse_ssh_keys_from_response(const char *response_text, size_t response_len, char ***keys_out, size_t *num_keys, size_t max_keys)
Parse SSH keys from HTTPS response text.
Definition https_keys.c:297

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, build_github_ssh_url(), ERROR_INVALID_PARAM, MAX_CLIENTS, parse_ssh_keys_from_response(), SAFE_FREE, and SET_ERRNO.

Referenced by fetch_github_keys(), and parse_public_keys().

◆ fetch_gitlab_gpg_keys()

asciichat_error_t fetch_gitlab_gpg_keys ( const char * username,
char *** keys_out,
size_t * num_keys )

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

Fetch GPG keys from GitLab using HTTPS.

Fetch GPG keys from GitLab using BearSSL.

Parameters
usernameGitLab username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitLab: GET https://gitlab.com/username.gpg

Note
Network operation: Requires network connectivity and valid GitLab username. May fail if network is unavailable or username doesn't exist.
GPG format: Fetches GPG keys in armored format. Response contains GPG key blocks (--—BEGIN PGP PUBLIC KEY BLOCK--—).
Memory management: Caller must free each key string and the keys array (same as fetch_gitlab_ssh_keys).
Warning
Network dependency: Requires active network connection.
GPG support: GPG key parsing may not work until GPG support is re-enabled.
Parameters
usernameGitLab username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of GPG keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitLab: GET https://gitlab.com/username.gpg

Note
Memory management: Caller must free each key string and the keys array (same as fetch_gitlab_keys).
Warning
Network dependency: Requires active network connection.

Fetch GPG keys from GitLab using HTTPS.

Parameters
usernameGitLab username (must not be NULL)
keys_outOutput array of GPG key strings (caller must free each string and array)
num_keysOutput parameter for number of GPG keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches GPG keys from GitLab: GET https://gitlab.com/username.gpg

Note
Memory management: Caller must free each key string and the keys array (same as fetch_gitlab_keys).
Warning
Network dependency: Requires active network connection.

Definition at line 263 of file https_keys.c.

263 {
264 if (!username || !keys_out || !num_keys) {
265 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, keys_out=%p, num_keys=%p", username, keys_out, num_keys);
266 return ERROR_INVALID_PARAM;
267 }
268
269 // Build the GitLab GPG keys URL
270 char url[BUFFER_SIZE_SMALL];
271 asciichat_error_t url_result = build_gitlab_gpg_url(username, url, sizeof(url));
272 if (url_result != ASCIICHAT_OK) {
273 return url_result;
274 }
275
276 // Fetch the keys using HTTPS
277 char *response_text = NULL;
278 size_t response_len = 0;
279 asciichat_error_t fetch_result = https_fetch_keys(url, &response_text, &response_len);
280 if (fetch_result != ASCIICHAT_OK) {
281 return fetch_result;
282 }
283
284 // Parse GPG keys from the response
285 asciichat_error_t parse_result = parse_gpg_keys_from_response(response_text, response_len, keys_out, num_keys, MAX_CLIENTS);
286
287 // Clean up response text
288 SAFE_FREE(response_text);
289
290 return parse_result;
291}
asciichat_error_t build_gitlab_gpg_url(const char *username, char *url_out, size_t url_size)
Construct GitLab GPG keys URL.
Definition https_keys.c:140

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, build_gitlab_gpg_url(), ERROR_INVALID_PARAM, MAX_CLIENTS, parse_gpg_keys_from_response(), SAFE_FREE, and SET_ERRNO.

Referenced by fetch_gitlab_keys(), and parse_public_keys().

◆ fetch_gitlab_keys()

asciichat_error_t fetch_gitlab_keys ( const char * username,
char *** keys_out,
size_t * num_keys,
bool use_gpg )

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

Fetch SSH/GPG keys from GitLab using BearSSL.

Parameters
usernameGitLab username (must not be NULL)
keys_outOutput array of key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
use_gpgTrue to fetch GPG keys, false to fetch SSH keys
Returns
ASCIICHAT_OK on success, error code on failure

Fetches keys from GitLab:

Note
Network operation: Requires network connectivity and valid GitLab username. May fail if network is unavailable or username doesn't exist.
Memory management: Caller must free each key string and the keys array (same as fetch_github_keys).
Warning
Network dependency: Requires active network connection. May fail if GitLab is unreachable or username doesn't exist.

Definition at line 583 of file keys.c.

583 {
584 if (!username || !keys_out || !num_keys) {
585 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
586 }
587
588 if (use_gpg) {
589 return fetch_gitlab_gpg_keys(username, keys_out, num_keys);
590 } else {
591 return fetch_gitlab_ssh_keys(username, keys_out, num_keys);
592 }
593}

References ERROR_INVALID_PARAM, fetch_gitlab_gpg_keys(), fetch_gitlab_ssh_keys(), and SET_ERRNO.

◆ fetch_gitlab_ssh_keys()

asciichat_error_t fetch_gitlab_ssh_keys ( const char * username,
char *** keys_out,
size_t * num_keys )

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

Fetch SSH keys from GitLab using HTTPS.

Parameters
usernameGitLab username (must not be NULL)
keys_outOutput array of SSH key strings (caller must free each string and array)
num_keysOutput parameter for number of keys fetched
Returns
ASCIICHAT_OK on success, error code on failure

Fetches SSH keys from GitLab: GET https://gitlab.com/username.keys

Note
Network operation: Requires network connectivity and valid GitLab username. May fail if network is unavailable or username doesn't exist.
Key format: Only Ed25519 SSH keys are parsed from response. Other key types (RSA, ECDSA) are skipped.
Memory management: Caller must free each key string and the keys array (same as fetch_github_ssh_keys).
Warning
Network dependency: Requires active network connection. May fail if GitLab is unreachable or username doesn't exist.

Definition at line 203 of file https_keys.c.

203 {
204 if (!username || !keys_out || !num_keys) {
205 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: username=%p, keys_out=%p, num_keys=%p", username, keys_out, num_keys);
206 return ERROR_INVALID_PARAM;
207 }
208
209 // Build the GitLab SSH keys URL
210 char url[BUFFER_SIZE_SMALL];
211 asciichat_error_t url_result = build_gitlab_ssh_url(username, url, sizeof(url));
212 if (url_result != ASCIICHAT_OK) {
213 return url_result;
214 }
215
216 // Fetch the keys using HTTPS
217 char *response_text = NULL;
218 size_t response_len = 0;
219 asciichat_error_t fetch_result = https_fetch_keys(url, &response_text, &response_len);
220 if (fetch_result != ASCIICHAT_OK) {
221 return fetch_result;
222 }
223
224 // Parse SSH keys from the response
225 asciichat_error_t parse_result = parse_ssh_keys_from_response(response_text, response_len, keys_out, num_keys, MAX_CLIENTS);
226
227 // Clean up response text
228 SAFE_FREE(response_text);
229
230 return parse_result;
231}
asciichat_error_t build_gitlab_ssh_url(const char *username, char *url_out, size_t url_size)
Construct GitLab SSH keys URL.
Definition https_keys.c:90

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, build_gitlab_ssh_url(), ERROR_INVALID_PARAM, MAX_CLIENTS, parse_ssh_keys_from_response(), SAFE_FREE, and SET_ERRNO.

Referenced by fetch_gitlab_keys(), and parse_public_keys().

◆ format_gpg_key_display()

asciichat_error_t format_gpg_key_display ( const char * gpg_key_text,
char * output,
size_t output_size )

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

Format GPG key for display.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
outputOutput buffer for formatted key (must not be NULL)
output_sizeSize of output buffer (must be >= 64)
Returns
ASCIICHAT_OK on success, error code on failure

Formats GPG key for display by extracting key ID and creating display string.

Note
Display format: "GPG key ID: <hex_key_id>" (e.g., "GPG key ID: EDDAE1DA7360D7F4").
Key ID extraction: Uses get_gpg_key_id() to extract key ID. Falls back to generic message if extraction fails.
Buffer requirements: Output buffer must be at least 64 bytes. Format string is "GPG key ID: " (12 chars) + 16 hex chars + null = 29 bytes minimum.
Warning
GPG support is currently disabled. Function depends on get_gpg_key_id() which is not yet implemented. Falls back to generic message if extraction fails.

Definition at line 285 of file gpg_keys.c.

285 {
286 if (!gpg_key_text || !output) {
287 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, output=%p", gpg_key_text, output);
288 return ERROR_INVALID_PARAM;
289 }
290
291 if (output_size < 64) {
292 SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small: %zu (minimum 64)", output_size);
293 return ERROR_INVALID_PARAM;
294 }
295
296 // Extract key ID for display
297 uint8_t key_id[GPG_KEY_ID_SIZE];
298 asciichat_error_t key_id_result = get_gpg_key_id(gpg_key_text, key_id);
299 if (key_id_result != ASCIICHAT_OK) {
300 // Fallback to generic GPG key display
301 SAFE_STRNCPY(output, "GPG key (key ID extraction failed)", output_size - 1);
302 return ASCIICHAT_OK;
303 }
304
305 // Format as hex key ID
307 for (int i = 0; i < 8; i++) {
308 safe_snprintf(hex_key_id + i * 2, 3, "%02x", key_id[i]);
309 }
310 hex_key_id[16] = '\0';
311
312 // Create display string
313 int result = safe_snprintf(output, output_size, "GPG key ID: %s", hex_key_id);
314 if (result < 0 || result >= (int)output_size) {
315 SET_ERRNO(ERROR_STRING, "Failed to format GPG key display");
316 return ERROR_STRING;
317 }
318
319 return ASCIICHAT_OK;
320}
#define CRYPTO_GPG_GPG_KEYS_HEX_KEY_ID_BUFFER_SIZE
Definition gpg_keys.c:8
asciichat_error_t get_gpg_key_id(const char *gpg_key_text, uint8_t key_id_out[8])
Get GPG key ID (short fingerprint).
Definition gpg_keys.c:171
#define GPG_KEY_ID_SIZE
Definition sizes.h:173

References ASCIICHAT_OK, CRYPTO_GPG_GPG_KEYS_HEX_KEY_ID_BUFFER_SIZE, ERROR_INVALID_PARAM, ERROR_STRING, get_gpg_key_id(), GPG_KEY_ID_SIZE, SAFE_STRNCPY, and SET_ERRNO.

◆ format_public_key()

void format_public_key ( const public_key_t * key,
char * output,
size_t output_size )

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

Convert public key to display format (ssh-ed25519 or x25519 hex).

Parameters
keyPublic key to format (must not be NULL)
outputOutput buffer for formatted key string (must not be NULL)
output_sizeSize of output buffer (must be large enough for formatted key)

Formats public key for display:

  • Ed25519: "ssh-ed25519 AAAAC3..." (base64-encoded key)
  • X25519: "x25519 <hex>" (hex-encoded key)
Note
Output format: Depends on key type. Ed25519 uses base64, X25519 uses hex.
Buffer size: Output buffer should be at least 512 bytes for Ed25519 format. X25519 format requires at least 65 bytes (64 hex chars + "x25519 " prefix + null).
Warning
Output buffer must be large enough for formatted key string. Function does not check buffer size (may overflow).

Definition at line 672 of file keys.c.

672 {
673 if (!key || !output || output_size == 0) {
674 return;
675 }
676
677 if (key->type == KEY_TYPE_ED25519) {
678 // Format as SSH Ed25519 public key
679 // Simple base64 encoding for 32 bytes = 43 chars + padding
680 // For now, just use hex encoding
681 char hex_key[HEX_STRING_SIZE_32];
682 for (size_t i = 0; i < 32; i++) {
683 char hex_byte[3];
684 safe_snprintf(hex_byte, sizeof(hex_byte), "%02x", key->key[i]);
685 hex_key[i * 2] = hex_byte[0];
686 hex_key[i * 2 + 1] = hex_byte[1];
687 }
688 hex_key[64] = '\0';
689 safe_snprintf(output, output_size, "ssh-ed25519 %s %s", hex_key, key->comment);
690 } else if (key->type == KEY_TYPE_X25519) {
691 // Format as hex X25519 key
692 char hex_key[HEX_STRING_SIZE_32];
693 for (size_t i = 0; i < 32; i++) {
694 char hex_byte[3];
695 safe_snprintf(hex_byte, sizeof(hex_byte), "%02x", key->key[i]);
696 hex_key[i * 2] = hex_byte[0];
697 hex_key[i * 2 + 1] = hex_byte[1];
698 }
699 hex_key[64] = '\0';
700 safe_snprintf(output, output_size, "x25519 %s", hex_key);
701 } else {
702 safe_snprintf(output, output_size, "unknown key type: %d", key->type);
703 }
704}
char comment[MAX_COMMENT_LEN]
Definition key_types.h:79
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:158

References public_key_t::comment, HEX_STRING_SIZE_32, public_key_t::key, KEY_TYPE_ED25519, KEY_TYPE_X25519, and public_key_t::type.

◆ generate_key_fingerprint()

asciichat_error_t generate_key_fingerprint ( const public_key_t * key,
uint8_t * fingerprint_out,
size_t fingerprint_size )

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

Generate key fingerprint.

Parameters
keyKey to fingerprint (must not be NULL)
fingerprint_outOutput buffer for fingerprint (must not be NULL)
fingerprint_sizeSize of fingerprint buffer (must be >= 32 for SHA-256)
Returns
ASCIICHAT_OK on success, error code on failure

Generates key fingerprint by computing hash of key material. Typically uses SHA-256 for fingerprint generation.

Note
Fingerprint algorithm: Uses SHA-256 hash of key material. Fingerprint is 32 bytes (256 bits) for SHA-256.
Key material: Hashes raw 32-byte key data (not key type or comment). Fingerprint uniquely identifies the key.
Buffer requirements: Fingerprint buffer must be at least 32 bytes for SHA-256. Function may use different hash algorithms in the future.
Warning
Fingerprint buffer must be large enough for hash output. Function validates buffer size but may overflow if buffer is too small.

Definition at line 443 of file keys_validation.c.

443 {
444 if (!key || !fingerprint_out) {
445 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p, fingerprint_out=%p", key, fingerprint_out);
446 return ERROR_INVALID_PARAM;
447 }
448
449 if (fingerprint_size < 32) {
450 SET_ERRNO(ERROR_INVALID_PARAM, "Fingerprint buffer too small: %zu (minimum 32)", fingerprint_size);
451 return ERROR_INVALID_PARAM;
452 }
453
454 // Generate SHA-256 fingerprint of the key
455 if (key_fingerprint_digest(key->key, fingerprint_out) != ASCIICHAT_OK) {
456 SET_ERRNO(ERROR_CRYPTO, "Failed to generate key fingerprint");
457 return ERROR_CRYPTO;
458 }
459
460 return ASCIICHAT_OK;
461}
@ ERROR_CRYPTO
Definition error_codes.h:97
asciichat_error_t key_fingerprint_digest(const uint8_t public_key[ED25519_PUBLIC_KEY_SIZE], uint8_t digest[KEYMASK_DIGEST_SIZE])
Definition keymask.c:11

References ASCIICHAT_OK, ERROR_CRYPTO, ERROR_INVALID_PARAM, public_key_t::key, key_fingerprint_digest(), and SET_ERRNO.

Referenced by check_key_fingerprint().

◆ get_gpg_fingerprint()

asciichat_error_t get_gpg_fingerprint ( const char * gpg_key_text,
uint8_t fingerprint_out[20] )

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

Get GPG key fingerprint.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
fingerprint_outOutput buffer for fingerprint (20 bytes for SHA-1, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts GPG key fingerprint (SHA-1 hash of key material). Used for key identification and verification.

Note
Fingerprint format: SHA-1 hash of key material (20 bytes). Standard GPG fingerprint format.
OpenPGP parsing: Parses OpenPGP packet structure and computes SHA-1 hash. Requires parsing of packet structure.
Warning
NOT YET IMPLEMENTED: This function is not yet implemented. Returns ERROR_CRYPTO_KEY with "GPG fingerprint extraction not yet implemented".
GPG support is currently disabled. Function will not work until implemented.

Definition at line 158 of file gpg_keys.c.

158 {
159 if (!gpg_key_text || !fingerprint_out) {
160 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, fingerprint_out=%p", gpg_key_text, fingerprint_out);
161 return ERROR_INVALID_PARAM;
162 }
163
164 // TODO: Implement GPG fingerprint extraction
165 // This requires parsing the OpenPGP packet structure and computing SHA-1
166
167 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG fingerprint extraction not yet implemented");
168 return ERROR_CRYPTO_KEY;
169}

References ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, GPG_FINGERPRINT_SIZE, and SET_ERRNO.

◆ get_gpg_key_id()

asciichat_error_t get_gpg_key_id ( const char * gpg_key_text,
uint8_t key_id_out[8] )

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

Get GPG key ID (short fingerprint).

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
key_id_outOutput buffer for key ID (8 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts GPG key ID (last 8 bytes of SHA-1 fingerprint). Used for key identification in short form.

Note
Key ID format: Last 8 bytes of SHA-1 fingerprint (16 hex chars). Example: "EDDAE1DA7360D7F4"
Key ID extraction: Computes full fingerprint and extracts last 8 bytes. Alternatively, can parse from GPG key structure directly.
Warning
NOT YET IMPLEMENTED: This function is not yet implemented. Returns ERROR_CRYPTO_KEY with "GPG key ID extraction not yet implemented".
GPG support is currently disabled. Function will not work until implemented.

Definition at line 171 of file gpg_keys.c.

171 {
172 if (!gpg_key_text || !key_id_out) {
173 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, key_id_out=%p", gpg_key_text, key_id_out);
174 return ERROR_INVALID_PARAM;
175 }
176
177 // TODO: Implement GPG key ID extraction
178 // This is typically the last 8 bytes of the fingerprint
179
180 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key ID extraction not yet implemented");
181 return ERROR_CRYPTO_KEY;
182}

References ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, GPG_KEY_ID_SIZE, and SET_ERRNO.

Referenced by format_gpg_key_display().

◆ gpg_to_x25519_public()

asciichat_error_t gpg_to_x25519_public ( const char * gpg_key_text,
uint8_t x25519_pk[32] )

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

Convert GPG key to X25519 for key exchange.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
x25519_pkOutput buffer for X25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Converts GPG key to X25519 format for Diffie-Hellman key exchange. Extracts Ed25519 key and converts to X25519.

Note
Conversion flow:
  1. Extract Ed25519 public key from GPG key
  2. Convert Ed25519 to X25519 using libsodium
Key conversion: Uses crypto_sign_ed25519_pk_to_curve25519() from libsodium. Conversion is mathematically safe (same curve, different representation).
Warning
GPG support is currently disabled. Function depends on extract_ed25519_from_gpg() which is not yet implemented. Function will not work until GPG support is re-enabled.

Definition at line 132 of file gpg_keys.c.

132 {
133 if (!gpg_key_text || !x25519_pk) {
134 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_text=%p, x25519_pk=%p", gpg_key_text, x25519_pk);
135 return ERROR_INVALID_PARAM;
136 }
137
138 // First extract the Ed25519 public key from the GPG key
140 asciichat_error_t extract_result = extract_ed25519_from_gpg(gpg_key_text, ed25519_pk);
141 if (extract_result != ASCIICHAT_OK) {
142 return extract_result;
143 }
144
145 // Convert Ed25519 to X25519
146 if (crypto_sign_ed25519_pk_to_curve25519(x25519_pk, ed25519_pk) != 0) {
147 SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to convert Ed25519 to X25519");
148 return ERROR_CRYPTO_KEY;
149 }
150
151 return ASCIICHAT_OK;
152}
asciichat_error_t extract_ed25519_from_gpg(const char *gpg_key_id, uint8_t ed25519_pk[32])
Extract Ed25519 public key from GPG key.
Definition gpg_keys.c:116
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:37

References ASCIICHAT_OK, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, extract_ed25519_from_gpg(), SET_ERRNO, and X25519_KEY_SIZE.

◆ hex_decode()

asciichat_error_t hex_decode ( const char * hex,
uint8_t * output,
size_t output_len )

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

Decode hex string to binary (utility function for testing).

Parameters
hexHex string to decode (must not be NULL, must have even length)
outputOutput buffer for binary data (must not be NULL)
output_lenExpected output length in bytes (hex string must be output_len * 2 chars)
Returns
ASCIICHAT_OK on success, error code on failure

Decodes hex string to binary data. Utility function primarily for testing.

Note
Hex format: Must contain only valid hex characters (0-9, a-f, A-F). Must have even length (2 chars per byte).
Length validation: Hex string must be exactly output_len * 2 characters. Returns error if length doesn't match.
Invalid characters: Returns error if hex string contains invalid characters.
Warning
Hex string must have even length. Odd-length strings return error.

Definition at line 710 of file keys.c.

710 {
711 if (!hex || !output) {
712 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
713 }
714
715 size_t hex_len = strlen(hex);
716 size_t expected_hex_len = output_len * 2;
717
718 if (hex_len != expected_hex_len) {
719 return SET_ERRNO(ERROR_INVALID_PARAM, "Hex string length (%zu) doesn't match expected output length (%zu * 2 = %zu)", hex_len, output_len, expected_hex_len);
720 }
721
722 // Decode hex string to binary
723 for (size_t i = 0; i < output_len; i++) {
724 char hex_byte[3] = {hex[i * 2], hex[i * 2 + 1], '\0'};
725 char *endptr;
726 unsigned long byte = strtoul(hex_byte, &endptr, 16);
727
728 // Validate hex character
729 if (*endptr != '\0' || byte > 255) {
730 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid hex character at position %zu: '%c%c'", i * 2, hex[i * 2], hex[i * 2 + 1]);
731 }
732
733 output[i] = (uint8_t)byte;
734 }
735
736 return ASCIICHAT_OK;
737}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

Referenced by parse_public_key().

◆ parse_gpg_key()

asciichat_error_t parse_gpg_key ( const char * gpg_key_text,
public_key_t * key_out )

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

Parse GPG key from armored text format.

Parse Ed25519 public key from PGP armored format.

Parameters
gpg_key_textGPG key in armored format (--—BEGIN PGP PUBLIC KEY BLOCK--—, must not be NULL)
key_outOutput structure for parsed public key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses GPG key from armored format and extracts Ed25519 public key. Converts to X25519 for key exchange.

Note
GPG format: Expects PEM-armored GPG key format. Format: "-----BEGIN PGP PUBLIC KEY BLOCK-----" ... "-----END PGP PUBLIC KEY BLOCK-----"
Ed25519 extraction: Extracts Ed25519 public key from GPG key structure. Parses OpenPGP packet structure to find Ed25519 subkey.
Key conversion: Converts extracted Ed25519 key to X25519 for key exchange. Uses libsodium's conversion function.
Key validation: Validates GPG key format before parsing. Returns error if format is invalid.
Warning
GPG support is currently disabled. Many underlying functions are not implemented. This function may not work until GPG support is re-enabled.
Key format: Only Ed25519 GPG keys are supported. RSA/ECDSA GPG keys will return error.
Parameters
gpg_key_textGPG key in armored format (must not be NULL)
key_outOutput structure for parsed public key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts Ed25519 public key from PGP armored format. Parses GPG key structure and converts to Ed25519/X25519 format.

Note
Key format: GPG keys are parsed from armored format (--—BEGIN PGP PUBLIC KEY BLOCK--—). Extracts Ed25519 subkey and converts to X25519 for key exchange.

Parse GPG key from armored text format.

Parameters
gpg_key_textGPG key in armored format (must not be NULL)
key_outOutput structure for parsed public key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Extracts Ed25519 public key from PGP armored format. Parses GPG key structure and converts to Ed25519/X25519 format.

Note
Key format: GPG keys are parsed from armored format (--—BEGIN PGP PUBLIC KEY BLOCK--—). Extracts Ed25519 subkey and converts to X25519 for key exchange.

Definition at line 32 of file gpg_keys.c.

32 {
33 if (!gpg_key_id || !key_out) {
34 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_id=%p, key_out=%p", gpg_key_id, key_out);
36 }
37
38 // Validate key ID format (must be 8, 16, or 40 hex characters, optionally with 0x prefix)
39 // - 8 chars: short key ID (last 8 chars of fingerprint)
40 // - 16 chars: long key ID (last 16 chars of fingerprint)
41 // - 40 chars: full fingerprint
42 const char *key_id = gpg_key_id;
43 if (strncmp(key_id, "0x", 2) == 0 || strncmp(key_id, "0X", 2) == 0) {
44 key_id += 2; // Skip 0x prefix
45 }
46
47 size_t key_id_len = strlen(key_id);
48 if (key_id_len != 8 && key_id_len != 16 && key_id_len != 40) {
49 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID length: %zu (expected 8, 16, or 40 hex chars)", key_id_len);
50 }
51
52 // Validate hex characters
53 for (size_t i = 0; i < key_id_len; i++) {
54 char c = key_id[i];
55 if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
56 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID: contains non-hex character '%c'", c);
57 }
58 }
59
60 // Extract Ed25519 public key from GPG keyring using gpg --list-keys
62 asciichat_error_t extract_result = extract_ed25519_from_gpg(key_id, ed25519_pk);
63 if (extract_result != ASCIICHAT_OK) {
64 return extract_result;
65 }
66
67 // Initialize the public key structure
68 memset(key_out, 0, sizeof(public_key_t));
69 key_out->type = KEY_TYPE_GPG;
70 memcpy(key_out->key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
71
72 // Set comment for display
73 safe_snprintf(key_out->comment, sizeof(key_out->comment), "GPG key %s", key_id);
74
75 return ASCIICHAT_OK;
76}

References ASCIICHAT_OK, public_key_t::comment, ED25519_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, extract_ed25519_from_gpg(), public_key_t::key, KEY_TYPE_GPG, SET_ERRNO, and public_key_t::type.

Referenced by parse_public_key().

◆ parse_gpg_key_binary()

asciichat_error_t parse_gpg_key_binary ( const uint8_t * gpg_key_binary,
size_t key_size,
public_key_t * key_out )

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

Parse GPG key from binary format.

Parameters
gpg_key_binaryGPG key in binary format (must not be NULL)
key_sizeSize of binary key data (must be > 0)
key_outOutput structure for parsed public key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses GPG key from binary format (raw OpenPGP packets). Extracts Ed25519 public key and converts to X25519.

Note
Binary format: Accepts raw OpenPGP packet structure. Must parse packet structure to find Ed25519 public key packet.
OpenPGP packets: Parses OpenPGP packet format to extract public key. Requires understanding of OpenPGP packet structure.
Warning
NOT YET IMPLEMENTED: This function is not yet implemented. Returns ERROR_CRYPTO_KEY with "Binary GPG key parsing not yet implemented".
GPG support is currently disabled. Function will not work until implemented.

Definition at line 78 of file gpg_keys.c.

78 {
79 if (!gpg_key_binary || !key_out) {
80 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: gpg_key_binary=%p, key_out=%p", gpg_key_binary, key_out);
82 }
83
84 if (key_size == 0) {
85 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid key size: %zu", key_size);
87 }
88
90 asciichat_error_t result;
91 if (key_size >= strlen("-----BEGIN PGP PUBLIC KEY BLOCK-----") && memcmp(gpg_key_binary, "-----BEGIN PGP PUBLIC KEY BLOCK-----", strlen("-----BEGIN PGP PUBLIC KEY BLOCK-----")) == 0) {
92 char *armored_text = SAFE_MALLOC(key_size + 1, char *);
93 memcpy(armored_text, gpg_key_binary, key_size);
94 armored_text[key_size] = '\0';
95 result = openpgp_parse_armored_pubkey(armored_text, ed25519_pk);
96 SAFE_FREE(armored_text);
97 } else {
98 result = openpgp_parse_binary_pubkey(gpg_key_binary, key_size, ed25519_pk);
99 }
100
101 if (result != ASCIICHAT_OK) {
102 return result;
103 }
104
105 // Initialize the public key structure
106 memset(key_out, 0, sizeof(public_key_t));
107 key_out->type = KEY_TYPE_GPG;
108 memcpy(key_out->key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
109
110 // Set comment for display
111 safe_snprintf(key_out->comment, sizeof(key_out->comment), "GPG Ed25519 key");
112
113 return ASCIICHAT_OK;
114}
#define SAFE_MALLOC(size, cast)
asciichat_error_t openpgp_parse_binary_pubkey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:280
asciichat_error_t openpgp_parse_armored_pubkey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition openpgp.c:307

References ASCIICHAT_OK, public_key_t::comment, ED25519_PUBLIC_KEY_SIZE, ERROR_INVALID_PARAM, public_key_t::key, KEY_TYPE_GPG, openpgp_parse_armored_pubkey(), openpgp_parse_binary_pubkey(), SAFE_FREE, SAFE_MALLOC, SET_ERRNO, and public_key_t::type.

Referenced by parse_keys_from_file(), and parse_public_key().

◆ parse_gpg_keys_from_response()

asciichat_error_t parse_gpg_keys_from_response ( const char * response_text,
size_t response_len,
char *** keys_out,
size_t * num_keys,
size_t max_keys )

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

Parse GPG keys from HTTPS response text.

Parameters
response_textHTTPS response containing GPG keys (must not be NULL)
response_lenLength of response text
keys_outOutput array of parsed GPG keys (must not be NULL)
num_keysOutput parameter for number of keys parsed (must not be NULL)
max_keysMaximum number of keys to parse (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Parses GPG keys from HTTPS response text (armored format). Extracts GPG key blocks and allocates memory for each key string.

Note
Response format: Expects GPG keys in armored format. Format: "-----BEGIN PGP PUBLIC KEY BLOCK-----" ... "-----END PGP PUBLIC KEY BLOCK-----"
Key extraction: Finds GPG key blocks (BEGIN/END markers) and extracts each block. Allocates memory for each complete GPG key block.
Memory allocation: Allocates memory for each key string. Caller must free each string and the array.
Maximum keys: Stops parsing after max_keys keys are found. Function returns ASCIICHAT_OK even if more keys exist in response.
Warning
Memory leak: Caller must free returned strings and array. Function allocates memory that must be freed.
GPG support: GPG key parsing may not work until GPG support is re-enabled.

Definition at line 390 of file https_keys.c.

390 {
391 (void)max_keys;
392 if (!response_text || !keys_out || !num_keys) {
393 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for GPG key parsing");
394 return ERROR_INVALID_PARAM;
395 }
396
397 *num_keys = 0;
398 *keys_out = NULL;
399
400 // Check if this looks like a GPG key (starts with -----BEGIN PGP)
401 if (strncmp(response_text, "-----BEGIN PGP", 14) != 0) {
402 SET_ERRNO(ERROR_CRYPTO_KEY, "Response does not contain a valid GPG key");
403 return ERROR_CRYPTO_KEY;
404 }
405
406 // Write armored block to temp file
407 char temp_file[PLATFORM_MAX_PATH_LENGTH];
408 int fd = -1;
409 if (platform_create_temp_file(temp_file, sizeof(temp_file), "asc_gpg_import", &fd) != 0) {
410 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to create temp file for GPG import");
411 }
412
413#ifdef _WIN32
414 // On Windows, platform_create_temp_file returns fd=-1, need to open separately
415 fd = platform_open("https_key_temp", temp_file, O_WRONLY | O_BINARY);
416 if (fd < 0) {
417 platform_delete_temp_file(temp_file);
418 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open temp file for writing");
419 }
420#endif
421
422 ssize_t written = write(fd, response_text, response_len);
423 close(fd);
424
425 if (written != (ssize_t)response_len) {
426 platform_unlink(temp_file);
427 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to write GPG key to temp file");
428 }
429
430 // Import the key using gpg --import
431 char import_cmd[BUFFER_SIZE_MEDIUM];
432 safe_snprintf(import_cmd, sizeof(import_cmd), "gpg --import '%s' 2>&1", temp_file);
433 FILE *import_fp = NULL;
434 if (platform_popen("gpg_https_import", import_cmd, "r", &import_fp) != ASCIICHAT_OK || !import_fp) {
435 platform_unlink(temp_file);
436 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to run gpg --import");
437 }
438
440 size_t import_len = fread(import_output, 1, sizeof(import_output) - 1, import_fp);
441 import_output[import_len] = '\0';
442 platform_pclose(&import_fp);
443 platform_unlink(temp_file);
444
445 // Extract ALL key IDs from import output (format: "gpg: key KEYID: ...")
446 // GitHub often returns multiple keys in one armored block
447 const char *key_marker = "gpg: key ";
448 char key_ids[CRYPTO_HTTPS_KEYS_KEY_IDS_COUNT][GPG_KEY_ID_HEX_BUFFER_SIZE]; // Support up to 16 keys
449 size_t key_count = 0;
450
451 log_debug("GPG import output:\n%s", import_output);
452
453 char *search_pos = import_output;
454 while (key_count < 16) {
455 char *key_line = strstr(search_pos, key_marker);
456 if (!key_line)
457 break;
458
459 key_line += strlen(key_marker);
460 int i = 0;
461 while (i < 16 && key_line[i] != ':' && key_line[i] != ' ' && key_line[i] != '\n') {
462 key_ids[key_count][i] = key_line[i];
463 i++;
464 }
465 key_ids[key_count][i] = '\0';
466
467 if (i > 0) {
468 log_debug("Extracted GPG key ID #%zu: %s", key_count, key_ids[key_count]);
469 key_count++;
470 }
471 search_pos = key_line + i;
472 }
473
474 if (key_count == 0) {
475 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to extract any key IDs from GPG import output");
476 }
477
478 log_debug("Total GPG keys extracted from import: %zu", key_count);
479
480 // Allocate array for results
481 *keys_out = SAFE_MALLOC(sizeof(char *) * key_count, char **);
482 if (!*keys_out) {
483 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate GPG keys array");
484 }
485
486 // Process each key ID to get full fingerprint
487 size_t valid_keys = 0;
488 defer_named(release_keys, {
489 for (size_t i = 0; i < valid_keys; i++) {
490 SAFE_FREE((*keys_out)[i]);
491 }
492 SAFE_FREE(*keys_out);
493 *keys_out = NULL;
494 });
495 for (size_t k = 0; k < key_count; k++) {
496 // Get full fingerprint from gpg --list-keys output
497 char list_cmd[BUFFER_SIZE_SMALL];
498 safe_snprintf(list_cmd, sizeof(list_cmd), "gpg --list-keys --with-colons --fingerprint '%s' " PLATFORM_SHELL_NULL_REDIRECT, key_ids[k]);
499 FILE *list_fp = NULL;
500 if (platform_popen("gpg_https_list", list_cmd, "r", &list_fp) != ASCIICHAT_OK || !list_fp) {
501 continue; // Skip this key if we can't list it
502 }
503
505 size_t list_len = fread(list_output, 1, sizeof(list_output) - 1, list_fp);
506 list_output[list_len] = '\0';
507 platform_pclose(&list_fp);
508
509 // Check if it contains an Ed25519 key (algorithm 22)
510 if (!strstr(list_output, ":22:") && !strstr(list_output, "ed25519")) {
511 continue; // Skip non-Ed25519 keys
512 }
513
514 // Extract full 40-character fingerprint from "fpr:" line
515 // Format: fpr:::::::::FINGERPRINT:
516 // The fingerprint is field 10 (after 9 colons)
517 char fingerprint[GPG_FINGERPRINT_HEX_BUFFER_SIZE] = {0};
518 const char *fpr_marker = "\nfpr:";
519 char *fpr_line = strstr(list_output, fpr_marker);
520 if (fpr_line) {
521 fpr_line += 1; // Skip the newline
522 // Count 9 colons from the start of the line
523 int colon_count = 0;
524 while (*fpr_line && colon_count < 9) {
525 if (*fpr_line == ':')
526 colon_count++;
527 fpr_line++;
528 }
529 // Now we should be at the start of the fingerprint
530 // Extract up to 40 hex characters
531 int fpr_len = 0;
532 while (fpr_len < 40 && fpr_line[fpr_len] && fpr_line[fpr_len] != ':' && fpr_line[fpr_len] != '\n') {
533 fingerprint[fpr_len] = fpr_line[fpr_len];
534 fpr_len++;
535 }
536 fingerprint[fpr_len] = '\0';
537 }
538
539 // If fingerprint extraction failed, use the short key ID
540 if (strlen(fingerprint) == 0) {
541 log_warn("Failed to extract fingerprint for key %s, using short key ID", key_ids[k]);
542 SAFE_STRNCPY(fingerprint, key_ids[k], sizeof(fingerprint));
543 }
544
545 log_debug("Key %s -> fingerprint: %s (length: %zu)", key_ids[k], fingerprint, strlen(fingerprint));
546
547 // Allocate and store this key in gpg:KEYID format
548 size_t gpg_key_len = strlen("gpg:") + strlen(fingerprint) + 1;
549 (*keys_out)[valid_keys] = SAFE_MALLOC(gpg_key_len, char *);
550 if (!(*keys_out)[valid_keys]) {
551 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate GPG key string");
552 }
553
554 safe_snprintf((*keys_out)[valid_keys], gpg_key_len, "gpg:%s", fingerprint);
555 log_debug("Added valid Ed25519 key #%zu: %s", valid_keys, (*keys_out)[valid_keys]);
556 valid_keys++;
557 }
558
559 if (valid_keys == 0) {
560 return SET_ERRNO(ERROR_CRYPTO_KEY, "No valid Ed25519 keys found in imported GPG keys");
561 }
562
563 *num_keys = valid_keys;
564 defer_cancel(release_keys);
565 return ASCIICHAT_OK;
566}
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
#define PLATFORM_MAX_PATH_LENGTH
@ ERROR_MEMORY
Definition error_codes.h:55
#define CRYPTO_HTTPS_KEYS_IMPORT_OUTPUT_BUFFER_SIZE
Definition https_keys.c:8
#define CRYPTO_HTTPS_KEYS_KEY_IDS_COUNT
Definition https_keys.c:9
#define CRYPTO_HTTPS_KEYS_LIST_OUTPUT_BUFFER_SIZE
Definition https_keys.c:10
#define GPG_FINGERPRINT_HEX_BUFFER_SIZE
Definition sizes.h:172
#define GPG_KEY_ID_HEX_BUFFER_SIZE
Definition sizes.h:174

References ASCIICHAT_OK, BUFFER_SIZE_MEDIUM, BUFFER_SIZE_SMALL, CRYPTO_HTTPS_KEYS_IMPORT_OUTPUT_BUFFER_SIZE, CRYPTO_HTTPS_KEYS_KEY_IDS_COUNT, CRYPTO_HTTPS_KEYS_LIST_OUTPUT_BUFFER_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, ERROR_MEMORY, GPG_FINGERPRINT_HEX_BUFFER_SIZE, GPG_KEY_ID_HEX_BUFFER_SIZE, log_debug, log_warn, PLATFORM_MAX_PATH_LENGTH, platform_open(), platform_pclose(), platform_popen(), SAFE_FREE, SAFE_MALLOC, SAFE_STRNCPY, and SET_ERRNO.

Referenced by fetch_github_gpg_keys(), and fetch_gitlab_gpg_keys().

◆ parse_keys_from_file()

asciichat_error_t parse_keys_from_file ( const char * path,
public_key_t * keys,
size_t * num_keys,
size_t max_keys )

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

Parse SSH keys from file (supports authorized_keys and known_hosts formats).

Parameters
pathPath to key file (must not be NULL)
keysOutput array for parsed public keys (must not be NULL)
num_keysOutput parameter for number of keys parsed (must not be NULL)
max_keysMaximum number of keys to parse (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Parses multiple SSH keys from file. Supports:

  • authorized_keys format: One key per line (ssh-ed25519 AAAAC3... comment)
  • .pub file with multiple entries: File containing multiple SSH public key entries, one per line (each line in ssh-ed25519 AAAAC3... comment format). This format is similar to authorized_keys and can contain any number of keys.
  • known_hosts format: Multiple keys per line (hostname ssh-ed25519 AAAAC3... comment)

File format examples:

# authorized_keys format or .pub file with multiple entries
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... alice@example.com
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... bob@example.com
Note
Key filtering: Only Ed25519 and X25519 keys are parsed. RSA/ECDSA keys are skipped (not supported).
File format: Automatically detects file format based on content. Supports both authorized_keys format (one key per line) and known_hosts format. Also supports .pub files containing multiple key entries (one per line).
Maximum keys: Stops parsing after max_keys keys are found. Function returns ASCIICHAT_OK even if more keys exist in file.
Warning
File must exist and be readable. Returns error if file cannot be opened.

Definition at line 599 of file keys.c.

599 {
600 if (!path || !keys || !num_keys || max_keys == 0) {
601 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for key file parsing");
602 }
603
604 *num_keys = 0;
605
606 if (!path_looks_like_path(path)) {
607 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid keys file path: %s", path);
608 }
609
610 char *normalized_path = NULL;
611 defer(SAFE_FREE(normalized_path));
612 asciichat_error_t path_result = path_validate_user_path(path, PATH_ROLE_CLIENT_KEYS, &normalized_path);
613 if (path_result != ASCIICHAT_OK) {
614 return path_result;
615 }
616
617 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
618 if (!f) {
619 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open keys file: %s", path);
620 }
621
622 defer(SAFE_FCLOSE(f));
623
624 char line[BUFFER_SIZE_LARGE];
625 bool has_first_line = fgets(line, sizeof(line), f) != NULL;
626 uint8_t first_packet = has_first_line ? (uint8_t)line[0] : 0;
627 unsigned int first_packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
628 if (has_first_line && (strstr(line, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL || first_packet_tag == 6u)) {
629 if (fseek(f, 0, SEEK_END) != 0) {
630 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek OpenPGP key file: %s", path);
631 }
632 long file_size = ftell(f);
633 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
634 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenPGP key file size: %ld bytes", file_size);
635 }
636 SAFE_MALLOC_DEFER_FREE(armored_key, (size_t)file_size + 1, char *);
637 size_t bytes_read = fread(armored_key, 1, (size_t)file_size, f);
638
639 if (bytes_read != (size_t)file_size) {
640 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read OpenPGP key file: %s", path);
641 }
642 asciichat_error_t result;
643 if (first_packet_tag == 6u) {
644 result = parse_gpg_key_binary((const uint8_t *)armored_key, bytes_read, &keys[0]);
645 } else {
646 armored_key[bytes_read] = '\0';
647 result = parse_public_key(armored_key, &keys[0]);
648 }
649
650 if (result == ASCIICHAT_OK)
651 *num_keys = 1;
652 return result;
653 }
654 rewind(f);
655 while (fgets(line, sizeof(line), f) && *num_keys < max_keys) {
656 // Remove newline
657 line[strcspn(line, "\r\n")] = 0;
658
659 // Skip empty lines and comments
660 if (strlen(line) == 0 || line[0] == '#') {
661 continue;
662 }
663
664 if (parse_public_key(line, &keys[*num_keys]) == ASCIICHAT_OK) {
665 (*num_keys)++;
666 }
667 }
668
669 return ASCIICHAT_OK;
670}
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define SAFE_MALLOC_DEFER_FREE(name, size, cast)
#define SAFE_FCLOSE(fp)
asciichat_error_t parse_gpg_key_binary(const uint8_t *gpg_key_binary, size_t key_size, public_key_t *key_out)
Parse GPG key from binary format.
Definition gpg_keys.c:78
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:495
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:705
@ PATH_ROLE_CLIENT_KEYS
Definition path.h:327

References ASCIICHAT_OK, BUFFER_SIZE_LARGE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, parse_gpg_key_binary(), parse_public_key(), path_looks_like_path(), PATH_ROLE_CLIENT_KEYS, path_validate_user_path(), platform_fopen(), SAFE_FCLOSE, SAFE_FREE, SAFE_MALLOC_DEFER_FREE, and SET_ERRNO.

Referenced by parse_public_keys().

◆ parse_private_key()

asciichat_error_t parse_private_key ( const char * path,
private_key_t * key_out )

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

Parse SSH private key from file.

Parameters
pathPath to private key file
key_outOutput structure for parsed private key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses private key from file. Supports:

  • OpenSSH Ed25519: ~/.ssh/id_ed25519 (OpenSSH Ed25519 format)
  • Raw hex file: File containing 64 hex chars for X25519 key
Note
Encrypted keys: If key is encrypted (has password), prompts for password and decrypts it using platform-specific password prompt.
SSH agent detection: If use_ssh_agent is true, key is loaded from SSH agent instead of file. Key stays in agent (not loaded into memory).
File permissions: Validates file permissions before parsing. Warns if file has overly permissive permissions (world-readable).
Key format: Currently only supports Ed25519 keys (OpenSSH format). RSA/ECDSA keys are NOT supported.
Warning
File permissions: Private key files should have restrictive permissions (0600). Function warns but does not fail on overly permissive permissions.

Definition at line 212 of file keys.c.

212 {
213 if (!key_path || !key_out) {
214 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for private key parsing");
215 }
216
217 // Clear output structure
218 memset(key_out, 0, sizeof(private_key_t));
219
220 // Check for GPG key format: "gpg:KEYID" where KEYID is 8, 16, or 40 hex chars
221 // - 8 chars: short key ID (last 8 chars of fingerprint)
222 // - 16 chars: long key ID (last 16 chars of fingerprint)
223 // - 40 chars: full fingerprint
224 if (strncmp(key_path, "gpg:", 4) == 0) {
225 const char *key_id = key_path + 4; // Skip "gpg:" prefix
226
227 // Validate key ID format (must be 8, 16, or 40 hex characters)
228 size_t key_id_len = strlen(key_id);
229 if (key_id_len != 8 && key_id_len != 16 && key_id_len != 40) {
230 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID length: %zu (expected 8, 16, or 40 hex chars)", key_id_len);
231 }
232
233 // Validate hex characters
234 for (size_t i = 0; i < key_id_len; i++) {
235 char c = key_id[i];
236 if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
237 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key ID: contains non-hex character '%c'", c);
238 }
239 }
240
241 // Get public key and keygrip from GPG keyring
243 char keygrip[MAX_GPG_KEYGRIP_LEN];
244 if (gpg_get_public_key(key_id, public_key, keygrip) != 0) {
245 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to get public key from GPG for key ID: %s", key_id);
246 }
247
248 // Populate private_key_t structure for GPG agent use
249 key_out->type = KEY_TYPE_ED25519;
250 key_out->use_gpg_agent = true;
251 key_out->use_ssh_agent = false;
252
253 // Store public key (for handshake and verification)
254 memcpy(key_out->public_key, public_key, ED25519_PUBLIC_KEY_SIZE);
255
256 // Store keygrip (for GPG agent signing operations)
257 platform_strncpy(key_out->gpg_keygrip, sizeof(key_out->gpg_keygrip), keygrip, sizeof(key_out->gpg_keygrip) - 1);
258
259 // Store comment for display
260 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG key %s", key_id);
261
262 // Clear the key.ed25519 field (we don't have the private key in memory)
263 // The private key stays protected in GPG agent
264 memset(key_out->key.ed25519, 0, ED25519_PRIVATE_KEY_SIZE);
265
266 // Set the public key in the second half of ed25519 key (standard Ed25519 format)
267 // This is for compatibility with code that expects the public key at offset 32
268 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, public_key, ED25519_PUBLIC_KEY_SIZE);
269
270 log_debug("Loaded GPG key %s (keygrip: %.40s) for agent signing", key_id, keygrip);
271 return ASCIICHAT_OK;
272 }
273
274 // Try to load file and detect format
275 char *normalized_path = NULL;
276 defer(SAFE_FREE(normalized_path));
277 asciichat_error_t path_result = path_validate_user_path(key_path, PATH_ROLE_KEY_PRIVATE, &normalized_path);
278 if (path_result != ASCIICHAT_OK) {
279 return path_result;
280 }
281
282 // Read file content to detect format
283 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
284 if (!f) {
285 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open private key file: %s", key_path);
286 }
287
288 // Read first 50 bytes to detect format
290 size_t bytes_read = fread(header, 1, sizeof(header) - 1, f);
291 header[bytes_read] = '\0';
292 fclose(f);
293
294 log_debug("Read %zu bytes from %s", bytes_read, key_path);
295
296 // Check for PGP armored secret key format
297 if (strstr(header, "-----BEGIN PGP PRIVATE KEY") != NULL || strstr(header, "-----BEGIN PGP SECRET KEY") != NULL) {
298 log_debug("Detected PGP armored secret key format in %s", key_path);
299 // Load entire file for OpenPGP parsing
300 f = platform_fopen("file_stream", normalized_path, "r");
301 if (!f) {
302 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open GPG key file: %s", key_path);
303 }
304
305 // Get file size
306 fseek(f, 0, SEEK_END);
307 long file_size = ftell(f);
308 fseek(f, 0, SEEK_SET);
309
310 if (file_size <= 0 || file_size > 1024 * 1024) { // Sanity check: max 1MB
311 fclose(f);
312
313 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid GPG key file size: %ld bytes", file_size);
314 }
315
316 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size + 1, char *);
317 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
318 file_content[content_read] = '\0';
319 fclose(f);
320
321 // Parse OpenPGP armored secret key
323 uint8_t ed25519_sk[ED25519_SEED_SIZE];
324 asciichat_error_t openpgp_result = openpgp_parse_armored_seckey(file_content, ed25519_pk, ed25519_sk);
325
326 if (openpgp_result != ASCIICHAT_OK) {
327 return openpgp_result;
328 }
329
330 // Populate private_key_t structure
331 key_out->type = KEY_TYPE_ED25519;
332 key_out->use_gpg_agent = false;
333 key_out->use_ssh_agent = false;
334
335 // Store keypair in Ed25519 format (64 bytes: 32-byte seed + 32-byte public key)
336 // libsodium expects the seed in first 32 bytes and public key in second 32 bytes
337 memcpy(key_out->key.ed25519, ed25519_sk, ED25519_SEED_SIZE); // Secret key (seed)
338 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, ed25519_pk, ED25519_PUBLIC_KEY_SIZE); // Public key
339 memcpy(key_out->public_key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE); // Also store in public_key field
340
341 // Store comment
342 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG Ed25519 key from %s", key_path);
343
344 log_debug("Loaded unencrypted GPG Ed25519 key from %s", key_path);
345 return ASCIICHAT_OK;
346 }
347
348 uint8_t first_packet = bytes_read > 0 ? (uint8_t)header[0] : 0;
349 unsigned int first_packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
350 if (bytes_read > 0 && first_packet_tag == 5u) {
351 f = platform_fopen("file_stream", normalized_path, "rb");
352 if (!f) {
353 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to open binary OpenPGP key file: %s", key_path);
354 }
355 if (fseek(f, 0, SEEK_END) != 0) {
356 (void)fclose(f);
357
358 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek binary OpenPGP key file: %s", key_path);
359 }
360 long file_size = ftell(f);
361 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
362 (void)fclose(f);
363
364 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid binary OpenPGP key file size: %ld bytes", file_size);
365 }
366 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size, uint8_t *);
367 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
368 (void)fclose(f);
369 if (content_read != (size_t)file_size) {
370 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read binary OpenPGP key file: %s", key_path);
371 }
372
374 uint8_t ed25519_sk[ED25519_SEED_SIZE];
375 asciichat_error_t openpgp_result = openpgp_parse_binary_seckey(file_content, content_read, ed25519_pk, ed25519_sk);
376 sodium_memzero(file_content, content_read);
377
378 if (openpgp_result != ASCIICHAT_OK)
379 return openpgp_result;
380
381 key_out->type = KEY_TYPE_ED25519;
382 key_out->use_gpg_agent = false;
383 key_out->use_ssh_agent = false;
384 memcpy(key_out->key.ed25519, ed25519_sk, ED25519_SEED_SIZE);
385 memcpy(key_out->key.ed25519 + ED25519_SEED_SIZE, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
386 memcpy(key_out->public_key, ed25519_pk, ED25519_PUBLIC_KEY_SIZE);
387 safe_snprintf(key_out->key_comment, sizeof(key_out->key_comment), "GPG Ed25519 key from %s", key_path);
388 sodium_memzero(ed25519_sk, sizeof(ed25519_sk));
389 return ASCIICHAT_OK;
390 }
391
392 // Fall back to SSH private key parsing
393 asciichat_error_t result = parse_ssh_private_key(normalized_path, key_out);
394
395 return result;
396}
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:104
key_type_t type
Definition key_types.h:102
bool use_gpg_agent
Definition key_types.h:108
char key_comment[MAX_COMMENT_LEN]
Definition key_types.h:110
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:109
char gpg_keygrip[MAX_GPG_KEYGRIP_LEN]
Definition key_types.h:111
asciichat_error_t parse_ssh_private_key(const char *key_path, private_key_t *key_out)
Parse SSH Ed25519 private key from file.
Definition ssh_keys.c:967
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:325
#define CRYPTO_KEYS_HEADER_BUFFER_SIZE
Definition keys.c:8
asciichat_error_t openpgp_parse_armored_seckey(const char *armored_text, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:733
asciichat_error_t openpgp_parse_binary_seckey(const uint8_t *data, size_t data_len, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE], uint8_t ed25519_sk[ED25519_SEED_SIZE])
Definition openpgp.c:702
#define ED25519_SEED_SIZE
Definition sizes.h:169
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:39
int platform_strncpy(char *dest, size_t dest_size, const char *src, size_t count)

References ASCIICHAT_OK, CRYPTO_KEYS_HEADER_BUFFER_SIZE, private_key_t::ed25519, ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, ED25519_SEED_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, gpg_get_public_key(), private_key_t::gpg_keygrip, private_key_t::key, private_key_t::key_comment, KEY_TYPE_ED25519, log_debug, MAX_GPG_KEYGRIP_LEN, openpgp_parse_armored_seckey(), openpgp_parse_binary_seckey(), parse_ssh_private_key(), PATH_ROLE_KEY_PRIVATE, path_validate_user_path(), platform_fopen(), platform_strncpy(), private_key_t::public_key, SAFE_FREE, SAFE_MALLOC_DEFER_FREE, SET_ERRNO, private_key_t::type, private_key_t::use_gpg_agent, and private_key_t::use_ssh_agent.

Referenced by acip_security_init_options().

◆ parse_public_key()

asciichat_error_t parse_public_key ( const char * input,
public_key_t * key_out )

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

Parse SSH/GPG public key from any format (returns first key only).

Parameters
inputKey input in various formats (see below)
key_outOutput structure for parsed public key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses public key from various input formats:

Supported formats:

  • Raw base64 SSH key: "AAAAC3NzaC1lZDI1NTE5AAAAI..." (just the base64 part from .pub files, no prefix)
  • SSH Ed25519: "ssh-ed25519 AAAAC3... comment" (full SSH public key format)
  • HTTPS URL: "https://example.com/key.pub" or "https://example.com/key.gpg" (fetches from URL, parses response)
  • GitHub SSH: "github:username" (fetches from https://github.com/username.keys, returns first Ed25519 key)
  • GitLab SSH: "gitlab:username" (fetches from https://gitlab.com/username.keys, returns first Ed25519 key)
  • GitHub GPG: "github:username.gpg" (fetches GPG key from https://github.com/username.gpg)
  • GitLab GPG: "gitlab:username.gpg" (fetches GPG key from https://gitlab.com/username.gpg)
  • GPG keyring: "gpg:0xKEYID" (shells out to gpg --export KEYID)
  • File path: Path to .pub file or any file containing key (reads first line)
  • Raw hex: 64 hex chars for X25519 key

File support: When a file path is provided, the file is read and the first line is parsed as an SSH public key. Common formats:

  • .pub file: Standard SSH public key file (one key per file, reads first line)
  • Any text file: First line containing SSH key format is used
Note
Key normalization: All keys are converted to X25519 format for key exchange. Ed25519 keys are converted using libsodium conversion function.
GPG support: GPG Ed25519 keys are fully supported. Accepts 8, 16, or 40 character key IDs (short/long/full fingerprint). Requires gpg binary in PATH and gpg-agent running.
HTTPS URLs: Can be any HTTPS URL (e.g., https://discovery.ascii-chat.com/key.pub). Response content is parsed as key format. Uses BearSSL with system CA certificates. Requires network connectivity. Only first key is returned; for multiple keys, store them one per line in the response and use parse_public_keys() instead.
GitHub/GitLab fetching: Uses BearSSL for HTTPS requests. Requires network connectivity. Only first Ed25519 key is returned. For multiple keys, use parse_public_keys() instead.
File path: Reads first line of file and parses as SSH key format. File must exist and be readable. For files with multiple keys (one per line), use parse_keys_from_file() instead.
Warning
Network operations: GitHub/GitLab fetching requires network connectivity. May fail if network is unavailable or endpoints are blocked.

Definition at line 36 of file keys.c.

36 {
37 if (!input || !key_out) {
38 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for public key parsing");
39 }
40
41 // Clear output structure
42 memset(key_out, 0, sizeof(public_key_t));
43
44 // Try SSH key parsing first (full format with prefix)
45 if (strncmp(input, "ssh-ed25519", 11) == 0) {
46 key_out->type = KEY_TYPE_ED25519;
47 asciichat_error_t result = parse_ssh_ed25519_line(input, key_out->key);
48 if (result == ASCIICHAT_OK) {
49 platform_strncpy(key_out->comment, sizeof(key_out->comment), "ssh-ed25519", sizeof(key_out->comment) - 1);
50 }
51 return result;
52 }
53
54 // Try raw base64 SSH public key (without "ssh-ed25519" prefix)
55 // SSH Ed25519 public keys in base64 are typically ~68 characters
56 size_t input_len = strlen(input);
57 if (input_len >= 50 && input_len <= 80) {
58 // Check if it looks like base64 (only contains valid base64 chars)
59 bool looks_like_base64 = true;
60 for (size_t i = 0; i < input_len; i++) {
61 char c = input[i];
62 if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=')) {
63 looks_like_base64 = false;
64 break;
65 }
66 }
67
68 if (looks_like_base64) {
69 // Try to decode as SSH public key blob
70 SAFE_MALLOC_DEFER_FREE(blob, input_len, uint8_t *);
71 size_t blob_len = 0;
72
73 const char *end = NULL;
74 int decode_result = sodium_base642bin(blob, input_len, input, input_len,
75 NULL, // ignore chars
76 &blob_len, &end, sodium_base64_VARIANT_ORIGINAL);
77
78 if (decode_result == 0 && blob_len >= 47) { // Minimum size: 4+11+4+32 = 51 bytes
79 // Validate SSH key blob structure
80 // Format: [4 bytes: length][11 bytes: "ssh-ed25519"][4 bytes: length][32 bytes: key]
81 if (blob_len >= 4) {
82 uint32_t key_type_len = ((uint32_t)blob[0] << 24) | ((uint32_t)blob[1] << 16) | ((uint32_t)blob[2] << 8) | blob[3];
83 if (key_type_len == 11 && blob_len >= 15 && memcmp(blob + 4, "ssh-ed25519", 11) == 0) {
84 // Valid ssh-ed25519 blob, extract the 32-byte public key
85 if (blob_len >= 19) {
86 uint32_t pubkey_len = ((uint32_t)blob[15] << 24) | ((uint32_t)blob[16] << 16) | ((uint32_t)blob[17] << 8) | blob[18];
87 if (pubkey_len == 32 && blob_len >= 51) {
88 // Extract Ed25519 public key
89 key_out->type = KEY_TYPE_ED25519;
90 memcpy(key_out->key, blob + 19, CRYPTO_PUBLIC_KEY_SIZE);
91 platform_strncpy(key_out->comment, sizeof(key_out->comment), "raw-base64", sizeof(key_out->comment) - 1);
92 return ASCIICHAT_OK;
93 }
94 }
95 }
96 }
97 }
98 }
99 }
100
101 // Try GPG key parsing
102 if (strncmp(input, "gpg:", 4) == 0) {
103 return parse_gpg_key(input + 4, key_out);
104 }
105
106 // Try HTTPS URLs (validated via production-grade URL regex)
107 if (url_is_valid(input)) {
108 // Parse HTTPS URL to extract hostname and path
109 url_parts_t url_parts = {0};
110 asciichat_error_t parse_result = url_parse(input, &url_parts);
111 if (parse_result != ASCIICHAT_OK) {
112 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to parse HTTPS URL: %s", input);
113 }
114
115 // Fetch the key via HTTPS
116 char *response = https_get(url_parts.host, url_parts.path);
117 url_parts_destroy(&url_parts);
118
119 if (!response) {
120 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to fetch key from HTTPS URL: %s", input);
121 }
122
123 // Parse the fetched content as a public key
124 asciichat_error_t result = parse_public_key(response, key_out);
125 SAFE_FREE(response);
126 return result;
127 }
128
129 // Try HTTPS key fetching (GitHub/GitLab) - delegate to parse_public_keys and return first
130 if (strncmp(input, "github:", 7) == 0 || strncmp(input, "gitlab:", 7) == 0) {
131 public_key_t keys[1];
132 size_t num_keys = 0;
133 asciichat_error_t result = parse_public_keys(input, keys, &num_keys, 1);
134 if (result == ASCIICHAT_OK && num_keys > 0) {
135 *key_out = keys[0];
136 }
137 return result;
138 }
139
140 // Try raw hex key (64 hex chars = 32 bytes)
141 if (strlen(input) == 64) {
142 // Check if it's valid hex
143 bool is_valid_hex = true;
144 for (int i = 0; i < 64; i++) {
145 if (!((input[i] >= '0' && input[i] <= '9') || (input[i] >= 'a' && input[i] <= 'f') || (input[i] >= 'A' && input[i] <= 'F'))) {
146 is_valid_hex = false;
147 break;
148 }
149 }
150
151 if (is_valid_hex) {
152 // Assume it's a raw X25519 public key in hex (default for raw hex)
153 key_out->type = KEY_TYPE_X25519;
154 // Use hex_decode utility to safely decode hex string to binary
155 if (hex_decode(input, key_out->key, 32) != ASCIICHAT_OK) {
156 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to decode hex key");
157 }
158 platform_strncpy(key_out->comment, sizeof(key_out->comment), "raw-hex", sizeof(key_out->comment) - 1);
159 return ASCIICHAT_OK;
160 }
161 }
162
163 // Try PGP armored format (-----BEGIN PGP PUBLIC KEY BLOCK-----)
164 if (strstr(input, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL) {
165 return parse_gpg_key_binary((const uint8_t *)input, strlen(input), key_out);
166 }
167
168 if (path_looks_like_path(input)) {
169 char *normalized_path = NULL;
170 defer(SAFE_FREE(normalized_path));
171 asciichat_error_t path_result = path_validate_user_path(input, PATH_ROLE_KEY_PUBLIC, &normalized_path);
172 if (path_result != ASCIICHAT_OK) {
173 return path_result;
174 }
175
176 FILE *f = platform_fopen("file_stream", normalized_path, "rb");
177 if (f) {
178 defer(SAFE_FCLOSE(f));
179 char line[BUFFER_SIZE_LARGE];
180 if (fgets(line, sizeof(line), f)) {
181 uint8_t first_packet = (uint8_t)line[0];
182 unsigned int packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
183 bool armored_gpg = strstr(line, "-----BEGIN PGP PUBLIC KEY BLOCK-----") != NULL;
184 if (armored_gpg || packet_tag == 6u) {
185 if (fseek(f, 0, SEEK_END) != 0) {
186 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to seek OpenPGP public key file: %s", input);
187 }
188 long file_size = ftell(f);
189 if (file_size <= 0 || file_size > 1024 * 1024 || fseek(f, 0, SEEK_SET) != 0) {
190 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid OpenPGP public key file size: %ld bytes", file_size);
191 }
192 SAFE_MALLOC_DEFER_FREE(file_content, (size_t)file_size, uint8_t *);
193 size_t content_read = fread(file_content, 1, (size_t)file_size, f);
194 SAFE_FCLOSE(f);
195 if (content_read != (size_t)file_size) {
196 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to read OpenPGP public key file: %s", input);
197 }
198 asciichat_error_t result = parse_gpg_key_binary(file_content, content_read, key_out);
199 return result;
200 }
201 SAFE_FCLOSE(f);
202 // Remove newline
203 line[strcspn(line, "\r\n")] = 0;
204 return parse_public_key(line, key_out);
205 }
206 }
207 }
208
209 return SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key format: %s", input);
210}
asciichat_error_t parse_public_keys(const char *input, public_key_t *keys_out, size_t *num_keys, size_t max_keys)
Parse all SSH/GPG public keys from any format (returns all keys).
Definition keys.c:402
asciichat_error_t parse_gpg_key(const char *gpg_key_id, public_key_t *key_out)
Parse Ed25519 public key from PGP armored format.
Definition gpg_keys.c:32
asciichat_error_t hex_decode(const char *hex, uint8_t *output, size_t output_len)
Decode hex string to binary (utility function for testing).
Definition keys.c:710
char * https_get(const char *hostname, const char *path)
Perform HTTPS GET request.
void url_parts_destroy(url_parts_t *parts)
Free parsed URL components.
Definition url.c:299
bool url_is_valid(const char *url)
URL validation using shared parsing and ICU hostname checks.
Definition url.c:156
asciichat_error_t url_parse(const char *url, url_parts_t *parts_out)
Parse HTTP(S), WebSocket, and TCP URL into components.
Definition url.c:163
@ PATH_ROLE_KEY_PUBLIC
Definition path.h:326
#define CRYPTO_PUBLIC_KEY_SIZE
Public key size (X25519).
Definition sizes.h:71
asciichat_error_t parse_ssh_ed25519_line(const char *line, uint8_t ed25519_pk[ED25519_PUBLIC_KEY_SIZE])
Definition ssh_keys.c:165
Structure containing parsed URL components.
Definition url.h:69
char * path
Extracted path, query, and fragment (allocated if present, may be NULL).
Definition url.h:75
char * host
Canonical ASCII hostname or IP address (allocated).
Definition url.h:72

References ASCIICHAT_OK, BUFFER_SIZE_LARGE, public_key_t::comment, CRYPTO_PUBLIC_KEY_SIZE, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, hex_decode(), url_parts_t::host, https_get(), public_key_t::key, KEY_TYPE_ED25519, KEY_TYPE_X25519, parse_gpg_key(), parse_gpg_key_binary(), parse_public_key(), parse_public_keys(), parse_ssh_ed25519_line(), url_parts_t::path, path_looks_like_path(), PATH_ROLE_KEY_PUBLIC, path_validate_user_path(), platform_fopen(), platform_strncpy(), SAFE_FCLOSE, SAFE_FREE, SAFE_MALLOC_DEFER_FREE, SET_ERRNO, public_key_t::type, url_is_valid(), url_parse(), and url_parts_destroy().

Referenced by check_known_host_with_key(), discovery_keys_download_https(), discovery_keys_load_file(), discovery_keys_verify(), parse_keys_from_file(), parse_public_key(), and parse_public_keys().

◆ parse_public_keys()

asciichat_error_t parse_public_keys ( const char * input,
public_key_t * keys_out,
size_t * num_keys,
size_t max_keys )

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

Parse all SSH/GPG public keys from any format (returns all keys).

Parameters
inputKey input in various formats (see parse_public_key for supported formats)
keys_outOutput array for parsed public keys (must not be NULL)
num_keysOutput parameter for number of keys parsed (must not be NULL)
max_keysMaximum number of keys to parse (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Similar to parse_public_key(), but returns ALL keys for formats that support multiple keys:

Multiple key support:

  • GitHub SSH: "github:username" - returns ALL Ed25519 keys from user's profile
  • GitLab SSH: "gitlab:username" - returns ALL Ed25519 keys from user's profile
  • File path: Returns all keys from file (one per line)
  • Comma-separated list: "github:user1, /path/to/keys.pub, https://example.com/key.pub" - returns all keys from all sources

Single key formats (behaves like parse_public_key):

  • SSH Ed25519: "ssh-ed25519 AAAAC3..." - returns single key
  • Raw hex: 64 hex chars - returns single key
  • GPG formats: Returns single key

Comma-separated support: When input contains commas, each comma-separated specifier is parsed independently. Whitespace around commas is automatically trimmed. If any specifier fails to parse, that specifier is skipped with a warning, but parsing continues for remaining specifiers. Returns ASCIICHAT_OK if at least one specifier parsed successfully.

This function is useful when you need to verify against ANY of a user's keys, such as when a user has multiple SSH keys for different machines on their GitHub/GitLab account, or keys from multiple sources.

Note
GitHub/GitLab: Users often have multiple SSH keys for different machines. This function fetches all keys so you can verify against any of them.
Key filtering: Only Ed25519 keys are returned. RSA/ECDSA keys are skipped.
Warning
Network operations: GitHub/GitLab fetching requires network connectivity.

Definition at line 402 of file keys.c.

402 {
403 if (!input || !keys_out || !num_keys || max_keys == 0) {
404 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for multi-key parsing");
405 }
406
407 *num_keys = 0;
408
409 // Handle comma-separated key specifiers
410 if (strchr(input, ',') != NULL) {
411 size_t input_len = strlen(input);
412 char *input_copy = SAFE_MALLOC(input_len + 1, char *);
413 memcpy(input_copy, input, input_len + 1);
414
415 char *saveptr = NULL;
416 char *specifier = platform_strtok_r(input_copy, ",", &saveptr);
417
418 while (specifier != NULL && *num_keys < max_keys) {
419 // Trim leading/trailing whitespace
420 while (*specifier && isspace((unsigned char)*specifier)) {
421 specifier++;
422 }
423 char *end = specifier + strlen(specifier) - 1;
424 while (end > specifier && isspace((unsigned char)*end)) {
425 *end-- = '\0';
426 }
427
428 // Skip empty specifiers
429 if (strlen(specifier) > 0) {
430 // Recursively parse this single specifier (will not re-enter comma handling)
431 size_t current_num = 0;
432 asciichat_error_t result = parse_public_keys(specifier, &keys_out[*num_keys], &current_num, max_keys - *num_keys);
433 if (result == ASCIICHAT_OK && current_num > 0) {
434 *num_keys += current_num;
435 } else {
436 log_warn("Failed to parse key specifier: %s", specifier);
437 // Continue parsing remaining specifiers even if one fails
438 }
439 }
440
441 specifier = platform_strtok_r(NULL, ",", &saveptr);
442 }
443
444 SAFE_FREE(input_copy);
445
446 if (*num_keys == 0) {
447 return SET_ERRNO(ERROR_CRYPTO_KEY, "No valid keys found in comma-separated list: %s", input);
448 }
449 return ASCIICHAT_OK;
450 }
451
452 // Check for direct SSH Ed25519 key format BEFORE checking for file paths
453 // (SSH keys can contain '/' in base64, which would match path_looks_like_path)
454 if (strncmp(input, "ssh-ed25519", 11) == 0) {
455 asciichat_error_t result = parse_public_key(input, &keys_out[0]);
456 if (result == ASCIICHAT_OK) {
457 *num_keys = 1;
458 }
459 return result;
460 }
461
462 // Check if this is a GitHub/GitLab reference - these support multiple keys
463 if (strncmp(input, "github:", 7) == 0 || strncmp(input, "gitlab:", 7) == 0) {
464 const char *username = input + 7; // Skip "github:" or "gitlab:"
465 bool is_github = (strncmp(input, "github:", 7) == 0);
466 bool is_gpg = (strstr(username, ".gpg") != NULL);
467
468 char **keys = NULL;
469 size_t num_fetched_keys = 0;
470 asciichat_error_t result;
471
472 if (is_github) {
473 if (is_gpg) {
474 result = fetch_github_gpg_keys(username, &keys, &num_fetched_keys);
475 } else {
476 result = fetch_github_ssh_keys(username, &keys, &num_fetched_keys);
477 }
478 } else {
479 if (is_gpg) {
480 result = fetch_gitlab_gpg_keys(username, &keys, &num_fetched_keys);
481 } else {
482 result = fetch_gitlab_ssh_keys(username, &keys, &num_fetched_keys);
483 }
484 }
485
486 if (result != ASCIICHAT_OK || num_fetched_keys == 0) {
487 return SET_ERRNO(ERROR_CRYPTO_KEY, "Failed to fetch keys from %s for user: %s", is_github ? "GitHub" : "GitLab", username);
488 }
489
490 // Parse each fetched key (only Ed25519 keys will succeed)
491 for (size_t i = 0; i < num_fetched_keys && *num_keys < max_keys; i++) {
492 if (parse_public_key(keys[i], &keys_out[*num_keys]) == ASCIICHAT_OK) {
493 (*num_keys)++;
494 }
495 // Non-Ed25519 keys are silently skipped
496 }
497
498 // Free the keys array
499 for (size_t i = 0; i < num_fetched_keys; i++) {
500 SAFE_FREE(keys[i]);
501 }
502 SAFE_FREE(keys);
503
504 if (*num_keys == 0) {
505 return SET_ERRNO(ERROR_CRYPTO_KEY, "No valid Ed25519 keys found for %s user: %s", is_github ? "GitHub" : "GitLab", username);
506 }
507
508 log_debug("Parsed %zu Ed25519 key(s) from %s user: %s", *num_keys, is_github ? "GitHub" : "GitLab", username);
509 return ASCIICHAT_OK;
510 }
511
512 // For file paths, delegate to parse_keys_from_file
513 if (path_looks_like_path(input)) {
514 return parse_keys_from_file(input, keys_out, num_keys, max_keys);
515 }
516
517 // For all other formats, use single-key parsing
518 asciichat_error_t result = parse_public_key(input, &keys_out[0]);
519 if (result == ASCIICHAT_OK) {
520 *num_keys = 1;
521 }
522 return result;
523}

References ASCIICHAT_OK, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, fetch_github_gpg_keys(), fetch_github_ssh_keys(), fetch_gitlab_gpg_keys(), fetch_gitlab_ssh_keys(), log_debug, log_warn, parse_keys_from_file(), parse_public_key(), parse_public_keys(), path_looks_like_path(), SAFE_FREE, SAFE_MALLOC, and SET_ERRNO.

Referenced by acip_security_init_options(), crypto_handshake_client_key_exchange(), parse_public_key(), and parse_public_keys().

◆ parse_ssh_ed25519_line()

asciichat_error_t parse_ssh_ed25519_line ( const char * line,
uint8_t ed25519_pk[32] )

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

Parse SSH Ed25519 public key from "ssh-ed25519 AAAAC3..." format.

Parameters
lineSSH key line to parse (must not be NULL)
ed25519_pkOutput buffer for Ed25519 public key (32 bytes, must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses SSH Ed25519 public key from standard SSH public key format. Format: "ssh-ed25519 <base64_key> [comment]"

Note
Format: Expects "ssh-ed25519" prefix followed by base64-encoded public key. Optional comment after key is ignored.
Base64 decoding: Decodes base64 key to extract 32-byte Ed25519 public key. Validates key format and length.
Key size: Ed25519 public key is exactly 32 bytes. Returns error if decoded key is not 32 bytes.
Warning
Key format: Must start with "ssh-ed25519". Other key types (RSA, ECDSA) are NOT supported.

References ED25519_PUBLIC_KEY_SIZE.

◆ parse_ssh_keys_from_response()

asciichat_error_t parse_ssh_keys_from_response ( const char * response_text,
size_t response_len,
char *** keys_out,
size_t * num_keys,
size_t max_keys )

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

Parse SSH keys from HTTPS response text.

Parameters
response_textHTTPS response containing SSH keys (must not be NULL)
response_lenLength of response text
keys_outOutput array of parsed SSH keys (must not be NULL)
num_keysOutput parameter for number of keys parsed (must not be NULL)
max_keysMaximum number of keys to parse (must be > 0)
Returns
ASCIICHAT_OK on success, error code on failure

Parses SSH keys from HTTPS response text (one key per line). Extracts Ed25519 keys and allocates memory for each key string.

Note
Response format: Expects one SSH key per line. Format: "ssh-ed25519 AAAAC3... comment" (one key per line)
Key filtering: Only Ed25519 SSH keys are parsed. Other key types (RSA, ECDSA) are skipped.
Memory allocation: Allocates memory for each key string. Caller must free each string and the array.
Maximum keys: Stops parsing after max_keys keys are found. Function returns ASCIICHAT_OK even if more keys exist in response.
Warning
Memory leak: Caller must free returned strings and array. Function allocates memory that must be freed.

Definition at line 297 of file https_keys.c.

297 {
298 if (!response_text || !keys_out || !num_keys) {
299 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters for SSH key parsing");
300 return ERROR_INVALID_PARAM;
301 }
302
303 *num_keys = 0;
304 *keys_out = NULL;
305
306 // Count the number of SSH keys in the response
307 size_t key_count = 0;
308 const char *line_start = response_text;
309 const char *line_end;
310
311 while ((line_end = strchr(line_start, '\n')) != NULL) {
312 size_t line_len = line_end - line_start;
313 if (line_len > 0 && line_start[0] != '\r' && line_start[0] != '\n') {
314 key_count++;
315 }
316 line_start = line_end + 1;
317 }
318
319 // Handle last line if it doesn't end with newline
320 if (line_start < response_text + response_len) {
321 key_count++;
322 }
323
324 if (key_count == 0) {
325 SET_ERRNO(ERROR_CRYPTO_KEY, "No SSH keys found in response");
326 return ERROR_CRYPTO_KEY;
327 }
328
329 if (key_count > max_keys) {
330 key_count = max_keys;
331 }
332
333 // Allocate array for key strings
334 *keys_out = SAFE_MALLOC(sizeof(char *) * key_count, char **);
335 if (!*keys_out) {
336 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate SSH keys array");
337 }
338
339 // Parse each SSH key line
340 line_start = response_text;
341 size_t parsed_keys = 0;
342 defer_named(release_keys, {
343 for (size_t i = 0; i < parsed_keys; i++) {
344 SAFE_FREE((*keys_out)[i]);
345 }
346 SAFE_FREE(*keys_out);
347 *keys_out = NULL;
348 });
349
350 while (parsed_keys < key_count && (line_end = strchr(line_start, '\n')) != NULL) {
351 size_t line_len = line_end - line_start;
352
353 // Skip empty lines
354 if (line_len > 0 && line_start[0] != '\r' && line_start[0] != '\n') {
355 // Allocate space for this key line
356 (*keys_out)[parsed_keys] = SAFE_MALLOC(line_len + 1, char *);
357 if (!(*keys_out)[parsed_keys]) {
358 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate SSH key string");
359 }
360
361 // Copy the key line
362 memcpy((*keys_out)[parsed_keys], line_start, line_len);
363 (*keys_out)[parsed_keys][line_len] = '\0';
364
365 parsed_keys++;
366 }
367
368 line_start = line_end + 1;
369 }
370
371 // Handle last line if it doesn't end with newline
372 if (parsed_keys < key_count && line_start < response_text + response_len) {
373 size_t line_len = (response_text + response_len) - line_start;
374 if (line_len > 0) {
375 (*keys_out)[parsed_keys] = SAFE_MALLOC(line_len + 1, char *);
376 if (!(*keys_out)[parsed_keys]) {
377 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate SSH key string");
378 }
379 memcpy((*keys_out)[parsed_keys], line_start, line_len);
380 (*keys_out)[parsed_keys][line_len] = '\0';
381 parsed_keys++;
382 }
383 }
384
385 *num_keys = parsed_keys;
386 defer_cancel(release_keys);
387 return ASCIICHAT_OK;
388}

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

Referenced by fetch_github_ssh_keys(), and fetch_gitlab_ssh_keys().

◆ parse_ssh_private_key()

asciichat_error_t parse_ssh_private_key ( const char * key_path,
private_key_t * key_out )

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

Parse SSH Ed25519 private key from file.

Parameters
key_pathPath to SSH private key file (must not be NULL)
key_outOutput structure for parsed private key (must not be NULL)
Returns
ASCIICHAT_OK on success, error code on failure

Parses OpenSSH Ed25519 private key from file. Supports both encrypted and unencrypted keys.

Note
Key format: Supports OpenSSH private key format (openssh-key-v1). Format: "-----BEGIN OPENSSH PRIVATE KEY-----" ... "-----END OPENSSH PRIVATE KEY-----"
Encrypted keys: If key is encrypted, prompts for password and decrypts it natively. Uses bcrypt_pbkdf (from libsodium-bcrypt-pbkdf) + BearSSL AES (aes256-ctr/aes256-cbc) for OpenSSH format decryption. No external tools (ssh-keygen) required.
Key structure: Parses OpenSSH key structure:
  • Magic: "openssh-key-v1\0"
  • Ciphername: "none" for unencrypted, cipher name for encrypted
  • KDF name and options (for encrypted keys)
  • Number of keys (must be 1)
  • Public key (for verification)
  • Private key blob (decrypted if encrypted)
Ed25519 extraction: Extracts Ed25519 seed (32 bytes) and public key (32 bytes) from private key blob. Stores as 64-byte Ed25519 key (seed + public).
File validation: Validates file permissions before parsing. Warns if file has overly permissive permissions (world-readable).
Warning
Key format: Only Ed25519 keys are supported. RSA/ECDSA keys will return error.
File permissions: Private key files should have restrictive permissions (0600). Function warns but does not fail on overly permissive permissions.
Password: Encrypted keys require password for native decryption. Decryption is done using bcrypt_pbkdf + BearSSL AES (supports aes256-ctr and aes256-cbc). May fail if password is incorrect, KDF parameters are unsupported, or unsupported encryption cipher.

Definition at line 967 of file ssh_keys.c.

967 {
968 if (!key_path || !key_out) {
969 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p, key_out=%p", key_path, key_out);
970 }
971#ifndef EMSCRIPTEN_BUILD
972 if (ssh_private_key_from_agent(key_path, key_out))
973 return ASCIICHAT_OK;
974#endif
975
976 // Each stage retains the existing failure cleanup; later stages run only on success.
977 ssh_private_key_parse_t state = {0};
978 asciichat_error_t result = ssh_private_key_read_file(&state, key_path);
979 if (result != ASCIICHAT_OK)
980 return result;
981 result = ssh_private_key_decode_pem(&state, key_path);
982 if (result != ASCIICHAT_OK)
983 return result;
984 result = ssh_private_key_read_header(&state, key_path);
985 if (result != ASCIICHAT_OK)
986 return result;
987
988 if (state.is_encrypted) {
989#ifdef EMSCRIPTEN_BUILD
990 SAFE_FREE(state.key_blob);
991 SAFE_FREE(state.file_content);
992 return SET_ERRNO(ERROR_NOT_SUPPORTED, "Passphrase-protected SSH keys are not supported in the browser");
993#else
994 return ssh_private_key_parse_encrypted(&state, key_path, key_out);
995#endif
996 }
997
998 result = ssh_private_key_read_public(&state, key_path);
999 if (result != ASCIICHAT_OK)
1000 return result;
1001 result = ssh_private_key_read_private_header(&state, key_path);
1002 if (result != ASCIICHAT_OK)
1003 return result;
1004 return ssh_private_key_read_private(&state, key_path, key_out);
1005}
@ ERROR_NOT_SUPPORTED
Definition error_codes.h:73

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NOT_SUPPORTED, ssh_private_key_parse_t::file_content, ssh_private_key_parse_t::is_encrypted, ssh_private_key_parse_t::key_blob, SAFE_FREE, and SET_ERRNO.

Referenced by acds_identity_load(), browser_client_parse_ssh_private_key(), client_parse_ssh_private_key(), and parse_private_key().

◆ private_key_to_x25519()

asciichat_error_t private_key_to_x25519 ( const private_key_t * key,
uint8_t x25519_sk[32] )

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

Convert private key to X25519 for Diffie-Hellman key exchange.

Parameters
keyPrivate key to convert (must not be NULL)
x25519_skOutput buffer for X25519 private key (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Converts private key to X25519 format for key exchange:

  • Ed25519 → X25519: Uses libsodium conversion function (crypto_sign_ed25519_sk_to_curve25519)
  • X25519: Passthrough (key is already in X25519 format)
Note
Conversion: Ed25519 keys are converted using libsodium's conversion function. Conversion is mathematically safe (same curve, different representation).
Ed25519 keys: Extracts 32-byte seed from Ed25519 key (first 32 bytes of ed25519 union). Converts seed to X25519 scalar using libsodium.
X25519 passthrough: If key is already X25519, key is copied directly.
Warning
All keys must be 32 bytes. Function validates key size before conversion.

References X25519_KEY_SIZE.

◆ public_key_to_x25519()

asciichat_error_t public_key_to_x25519 ( const public_key_t * key,
uint8_t x25519_pk[32] )

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

Convert public key to X25519 for Diffie-Hellman key exchange.

Parameters
keyPublic key to convert (must not be NULL)
x25519_pkOutput buffer for X25519 public key (32 bytes)
Returns
ASCIICHAT_OK on success, error code on failure

Converts public key to X25519 format for key exchange:

  • Ed25519 → X25519: Uses libsodium conversion function (crypto_sign_ed25519_pk_to_curve25519)
  • X25519: Passthrough (key is already in X25519 format)
  • GPG: Already derived to X25519 during GPG parsing
Note
Conversion: Ed25519 keys are converted using libsodium's conversion function. Conversion is mathematically safe (same curve, different representation).
X25519 passthrough: If key is already X25519, key is copied directly.
GPG keys: GPG keys are already converted to X25519 during parsing. No additional conversion needed.
Warning
All keys must be 32 bytes. Function validates key size before conversion.

References X25519_KEY_SIZE.

◆ validate_gpg_key_format()

asciichat_error_t validate_gpg_key_format ( const char * gpg_key_text)

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

Validate GPG key format and structure.

Validate GPG key format.

Parameters
gpg_key_textGPG key text to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates GPG key format before parsing. Checks for correct armored format and basic structure.

Note
Format validation: Checks for correct armored format markers. Validates basic GPG key structure.
Use case: Called before parsing to ensure key format is valid. Returns error early if format is invalid.
Warning
GPG support is currently disabled. Function may not work until GPG support is re-enabled.
Parameters
key_textGPG key text to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates GPG key format by checking for correct armored format markers. Expects "-----BEGIN PGP PUBLIC KEY BLOCK-----" and "-----END PGP PUBLIC KEY BLOCK-----".

Note
Format validation: Checks for correct GPG armored format markers. Validates basic GPG key structure.
GPG format: Expects PEM-armored GPG key format. Format: "-----BEGIN PGP PUBLIC KEY BLOCK-----" ... "-----END PGP PUBLIC KEY BLOCK-----"
Warning
GPG support: GPG key validation may not work until GPG support is re-enabled.

Validate GPG key format and structure.

Parameters
key_textGPG key text to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates GPG key format by checking for correct armored format markers. Expects "-----BEGIN PGP PUBLIC KEY BLOCK-----" and "-----END PGP PUBLIC KEY BLOCK-----".

Note
Format validation: Checks for correct GPG armored format markers. Validates basic GPG key structure.
GPG format: Expects PEM-armored GPG key format. Format: "-----BEGIN PGP PUBLIC KEY BLOCK-----" ... "-----END PGP PUBLIC KEY BLOCK-----"
Warning
GPG support: GPG key validation may not work until GPG support is re-enabled.

Definition at line 184 of file keys_validation.c.

184 {
185 if (!key_text) {
186 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_text=%p", key_text);
187 return ERROR_INVALID_PARAM;
188 }
189
190 // Check for GPG armor header
191 if (strncmp(key_text, "-----BEGIN PGP", 14) != 0) {
192 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key does not start with armor header");
193 return ERROR_CRYPTO_KEY;
194 }
195
196 // Check for GPG armor footer
197 if (strstr(key_text, "-----END PGP") == NULL) {
198 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key does not contain armor footer");
199 return ERROR_CRYPTO_KEY;
200 }
201
202 // Additional GPG key validation
203 // Validate armor format (should have valid armor headers)
204 bool has_version_header = (strstr(key_text, "Version:") != NULL);
205 bool has_charset_header = (strstr(key_text, "Charset:") != NULL || strstr(key_text, "Version:") != NULL);
206
207 if (!has_version_header && !has_charset_header) {
208 // Missing common armor headers - might be incomplete
209 log_warn("GPG armor missing version/charset headers - key might be incomplete");
210 }
211
212 // Validate base64 content (keys must have non-empty body between headers and footer)
213 const char *start_pos = strstr(key_text, "\n\n");
214 const char *end_pos = strstr(key_text, "\n-----END");
215 if (start_pos && end_pos && start_pos < end_pos) {
216 // -2 for \n\n at start_pos; check for underflow before casting to size_t
217 ptrdiff_t diff = end_pos - start_pos - 2;
218 if (diff <= 0) {
219 SET_ERRNO(ERROR_CRYPTO_KEY, "GPG key has empty or malformed body content");
220 return ERROR_CRYPTO_KEY;
221 }
222 }
223
224 return ASCIICHAT_OK;
225}

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

◆ validate_key_security()

asciichat_error_t validate_key_security ( const char * key_path)

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

Validate key permissions and security.

Parameters
key_pathPath to key file (must not be NULL)
Returns
ASCIICHAT_OK if secure, error code on failure

Validates key file permissions and performs security checks. Combines permission validation with additional security checks.

Note
Permission checking: Validates file permissions using validate_key_permissions(). Checks that file has restrictive permissions (0600).
Security checks: Additional security checks would include:
  • Weak key pattern detection
  • Key strength validation
  • Known weak key detection These are not yet fully implemented (TODOs in implementation).
Warning
Security checks incomplete: Additional security checks (weak keys, etc.) are not yet fully implemented. Function currently only checks permissions.

Definition at line 131 of file keys_validation.c.

131 {
132 if (!key_path) {
133 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p", key_path);
134 return ERROR_INVALID_PARAM;
135 }
136
137 // Check file permissions
138 asciichat_error_t perm_result = platform_validate_key_file_permissions(key_path);
139 if (perm_result != ASCIICHAT_OK) {
140 return perm_result;
141 }
142
143 // Additional security checks have been implemented in check_key_strength()
144 // and check_key_patterns() functions. File permissions check is the critical one.
145 // Known weak keys database would require periodic updates and is beyond scope.
146
147 return ASCIICHAT_OK;
148}

References ASCIICHAT_OK, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ validate_private_key()

asciichat_error_t validate_private_key ( const private_key_t * key)

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

Validate a private key structure.

Parameters
keyPrivate key to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates private key structure by checking:

  • Key type is valid (Ed25519 or X25519)
  • Key data is not all zeros
  • Comment length is within limits
Note
Key type validation: Checks that key type is one of: KEY_TYPE_ED25519 or KEY_TYPE_X25519 GPG keys are NOT supported for private keys (only public).
Key size: Ed25519 private keys are 64 bytes (seed + public). X25519 private keys are 32 bytes. Function validates key size based on key type.
Zero key check: Rejects keys with all-zero key data. Zero keys are invalid and should not be used.
Comment validation: Checks that comment length is less than MAX_COMMENT_LEN.
Warning
Zero keys: Keys with all-zero data are rejected as invalid.

Definition at line 70 of file keys_validation.c.

70 {
71 if (!key) {
72 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p", key);
74 }
75
76 // Check key type
77 if (key->type == KEY_TYPE_UNKNOWN) {
78 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key type is unknown");
79 return ERROR_CRYPTO_KEY;
80 }
81
82 if (key->type != KEY_TYPE_ED25519 && key->type != KEY_TYPE_X25519) {
83 SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported private key type: %d", key->type);
84 return ERROR_CRYPTO_KEY;
85 }
86
87 // Check key data is not all zeros
88 bool is_zero = true;
89 size_t key_size = (key->type == KEY_TYPE_ED25519) ? 64 : 32;
90
91 for (size_t i = 0; i < key_size; i++) {
92 if (key->key.ed25519[i] != 0) {
93 is_zero = false;
94 break;
95 }
96 }
97
98 if (is_zero) {
99 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key data is all zeros");
100 return ERROR_CRYPTO_KEY;
101 }
102
103 // Check comment length
104 if (strlen(key->key_comment) >= MAX_COMMENT_LEN) {
105 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key comment too long: %zu (maximum %d)", strlen(key->key_comment), MAX_COMMENT_LEN - 1);
106 return ERROR_CRYPTO_KEY;
107 }
108
109 // Validate comment is valid UTF-8 (user-provided text in key files)
110 if (key->key_comment[0] != '\0' && !utf8_is_valid(key->key_comment)) {
111 SET_ERRNO(ERROR_CRYPTO_KEY, "Private key comment contains invalid UTF-8 sequence");
112 return ERROR_CRYPTO_KEY;
113 }
114
115 return ASCIICHAT_OK;
116}
bool utf8_is_valid(const char *str)
Check if a string is valid UTF-8.
Definition utf8.c:128
#define MAX_COMMENT_LEN
Definition sizes.h:176

References ASCIICHAT_OK, private_key_t::ed25519, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, private_key_t::key, private_key_t::key_comment, KEY_TYPE_ED25519, KEY_TYPE_UNKNOWN, KEY_TYPE_X25519, MAX_COMMENT_LEN, SET_ERRNO, private_key_t::type, and utf8_is_valid().

◆ validate_public_key()

asciichat_error_t validate_public_key ( const public_key_t * key)

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

Validate a public key structure.

Parameters
keyPublic key to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates public key structure by checking:

  • Key type is valid (Ed25519, X25519, or GPG)
  • Key data is not all zeros
  • Comment length is within limits
Note
Key type validation: Checks that key type is one of: KEY_TYPE_ED25519, KEY_TYPE_X25519, or KEY_TYPE_GPG
Zero key check: Rejects keys with all-zero key data. Zero keys are invalid and should not be used.
Comment validation: Checks that comment length is less than MAX_COMMENT_LEN. Comments can be up to 255 characters (including null terminator).
Warning
Zero keys: Keys with all-zero data are rejected as invalid.

Definition at line 24 of file keys_validation.c.

24 {
25 if (!key) {
26 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key=%p", key);
28 }
29
30 // Check key type
31 if (key->type == KEY_TYPE_UNKNOWN) {
32 SET_ERRNO(ERROR_CRYPTO_KEY, "Key type is unknown");
33 return ERROR_CRYPTO_KEY;
34 }
35
36 if (key->type != KEY_TYPE_ED25519 && key->type != KEY_TYPE_X25519 && key->type != KEY_TYPE_GPG) {
37 SET_ERRNO(ERROR_CRYPTO_KEY, "Unsupported key type: %d", key->type);
38 return ERROR_CRYPTO_KEY;
39 }
40
41 // Check key data is not all zeros
42 bool is_zero = true;
43 for (int i = 0; i < 32; i++) {
44 if (key->key[i] != 0) {
45 is_zero = false;
46 break;
47 }
48 }
49
50 if (is_zero) {
51 SET_ERRNO(ERROR_CRYPTO_KEY, "Key data is all zeros");
52 return ERROR_CRYPTO_KEY;
53 }
54
55 // Check comment length
56 if (strlen(key->comment) >= MAX_COMMENT_LEN) {
57 SET_ERRNO(ERROR_CRYPTO_KEY, "Key comment too long: %zu (maximum %d)", strlen(key->comment), MAX_COMMENT_LEN - 1);
58 return ERROR_CRYPTO_KEY;
59 }
60
61 // Validate comment is valid UTF-8 (user-provided text in key files)
62 if (key->comment[0] != '\0' && !utf8_is_valid(key->comment)) {
63 SET_ERRNO(ERROR_CRYPTO_KEY, "Key comment contains invalid UTF-8 sequence");
64 return ERROR_CRYPTO_KEY;
65 }
66
67 return ASCIICHAT_OK;
68}

References ASCIICHAT_OK, public_key_t::comment, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, public_key_t::key, KEY_TYPE_ED25519, KEY_TYPE_GPG, KEY_TYPE_UNKNOWN, KEY_TYPE_X25519, MAX_COMMENT_LEN, SET_ERRNO, public_key_t::type, and utf8_is_valid().

◆ validate_ssh_key_file()

asciichat_error_t validate_ssh_key_file ( const char * key_path)

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

Validate SSH key file before parsing.

Validate SSH key file permissions and format.

Parameters
key_pathPath to SSH key file (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates SSH key file before parsing. Checks:

  • File exists and is readable
  • File has valid SSH private key header ("-----BEGIN OPENSSH PRIVATE KEY-----")
  • File permissions are appropriate (warns if overly permissive)
Note
Permission checking: Checks file permissions on Unix systems. Warns if file has world-readable permissions but does not fail validation.
File header: Validates that file starts with correct SSH private key header. Returns error if header is missing or invalid.
Platform-specific: Permission checking is Unix-specific. Windows does not have Unix-style permissions.
Warning
File permissions: Private key files should have restrictive permissions (0600). Function warns but does not fail on overly permissive permissions.

Validate SSH key file before parsing.

Parameters
key_pathPath to SSH key file (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates SSH key file before parsing. Checks:

  • File exists and is readable
  • File has valid SSH private key header ("-----BEGIN OPENSSH PRIVATE KEY-----")
  • File permissions are appropriate (warns if overly permissive)
Note
Permission checking: Checks file permissions on Unix systems. Warns if file has world-readable permissions but does not fail validation.
File header: Validates that file starts with correct SSH private key header. Returns error if header is missing or invalid.
Platform-specific: Permission checking is Unix-specific. Windows does not have Unix-style permissions.
Warning
File permissions: Private key files should have restrictive permissions (0600). Function warns but does not fail on overly permissive permissions.

Definition at line 1007 of file ssh_keys.c.

1007 {
1008 if (!key_path) {
1009 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_path=%p", key_path);
1010 }
1011
1012 char *normalized_path = NULL;
1013 defer(SAFE_FREE(normalized_path));
1014#ifdef EMSCRIPTEN_BUILD
1015 // Browser callers stage imported key text at this private virtual-FS path;
1016 // native path expansion and whitelist checks do not apply to that sandbox.
1017 static const char wasm_key_prefix[] = "/tmp/ascii-chat-key-";
1018 if (strncmp(key_path, wasm_key_prefix, sizeof(wasm_key_prefix) - 1) != 0) {
1019 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid browser SSH key path");
1020 }
1021 const char *validated_path = key_path;
1022#else
1023 if (!path_looks_like_path(key_path)) {
1024 return SET_ERRNO(ERROR_CRYPTO_KEY, "Invalid SSH key path: %s", key_path);
1025 }
1026
1027 asciichat_error_t path_result = path_validate_user_path(key_path, PATH_ROLE_KEY_PRIVATE, &normalized_path);
1028 if (path_result != ASCIICHAT_OK) {
1029 return path_result;
1030 }
1031 const char *validated_path = normalized_path;
1032#endif
1033
1034 // Check if file exists and is readable
1035 FILE *test_file = platform_fopen("file_stream", validated_path, "rb");
1036 if (test_file == NULL) {
1037 return SET_ERRNO(ERROR_CRYPTO_KEY, "Cannot read key file: %s", key_path);
1038 }
1039
1040 // Check if this is an SSH key file or GPG armored key by looking for the header
1041 char header[BUFFER_SIZE_SMALL];
1042 bool is_valid_key_file = false;
1043 size_t header_len = fread(header, 1, sizeof(header) - 1, test_file);
1044 if (header_len > 0) {
1045 header[header_len] = '\0';
1046 if (strstr(header, "BEGIN OPENSSH PRIVATE KEY") != NULL || strstr(header, "BEGIN RSA PRIVATE KEY") != NULL || strstr(header, "BEGIN EC PRIVATE KEY") != NULL ||
1047 strstr(header, "BEGIN PGP PRIVATE KEY") != NULL || strstr(header, "BEGIN PGP SECRET KEY") != NULL) {
1048 is_valid_key_file = true;
1049 } else {
1050 uint8_t first_packet = (uint8_t)header[0];
1051 unsigned int packet_tag = (first_packet & 0x80u) ? ((first_packet & 0x40u) ? (first_packet & 0x3fu) : ((first_packet >> 2) & 0x0fu)) : 0u;
1052 is_valid_key_file = packet_tag == 5u;
1053 }
1054 }
1055 (void)fclose(test_file);
1056
1057 if (!is_valid_key_file) {
1058 return SET_ERRNO(ERROR_CRYPTO_KEY, "File is not a valid SSH or GPG key: %s", key_path);
1059 }
1060
1061 // Check permissions for SSH key files (should be 600 or 400)
1062#ifndef _WIN32
1063 struct stat st;
1064 if (stat(validated_path, &st) == 0) {
1065 if ((st.st_mode & SSH_KEY_PERMISSIONS_MASK) != 0) {
1066 NOTICE(DANGER, "UNSAFE PRIVATE KEY PERMISSIONS", "SSH key file %s has overly permissive permissions: %o.\nRun chmod 600 on this key file before retrying.", key_path, st.st_mode & 0777);
1067 return SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key file has overly permissive permissions: %s", key_path);
1068 }
1069 }
1070#endif
1071
1072 return ASCIICHAT_OK;
1073}
#define SSH_KEY_PERMISSIONS_MASK
#define NOTICE(severity, title,...)
Definition notice.h:56

References ASCIICHAT_OK, BUFFER_SIZE_SMALL, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, NOTICE, path_looks_like_path(), PATH_ROLE_KEY_PRIVATE, path_validate_user_path(), platform_fopen(), SAFE_FREE, SET_ERRNO, and SSH_KEY_PERMISSIONS_MASK.

◆ validate_ssh_key_format()

asciichat_error_t validate_ssh_key_format ( const char * key_text)

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

Validate SSH key format.

Parameters
key_textSSH key text to validate (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates SSH key format by checking for correct format markers. Expects "ssh-ed25519 " prefix followed by base64-encoded key.

Note
Format validation: Checks that key text starts with "ssh-ed25519 ". Validates basic SSH key format structure.
Key type: Only Ed25519 SSH keys are validated. Other key types (RSA, ECDSA) will fail validation.
Warning
Key format: Must start with "ssh-ed25519 ". Other SSH key types (RSA, ECDSA) are NOT supported.

Definition at line 154 of file keys_validation.c.

154 {
155 if (!key_text) {
156 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_text=%p", key_text);
157 return ERROR_INVALID_PARAM;
158 }
159
160 // Check for SSH key format
161 if (strncmp(key_text, "ssh-ed25519 ", 12) != 0) {
162 SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key does not start with 'ssh-ed25519 '");
163 return ERROR_CRYPTO_KEY;
164 }
165
166 // Check for base64 data
167 const char *base64_start = key_text + 12;
168 while (*base64_start == ' ' || *base64_start == '\t') {
169 base64_start++;
170 }
171
172 if (*base64_start == '\0' || *base64_start == '\n' || *base64_start == '\r') {
173 SET_ERRNO(ERROR_CRYPTO_KEY, "SSH key has no base64 data");
174 return ERROR_CRYPTO_KEY;
175 }
176
177 // Additional comprehensive SSH key validation (base64, blob structure, etc.)
178 // would require full OpenSSH format parsing. Basic format check above is sufficient
179 // to catch malformed keys. Full validation happens during key loading.
180
181 return ASCIICHAT_OK;
182}

References ASCIICHAT_OK, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ validate_x25519_key_format()

asciichat_error_t validate_x25519_key_format ( const char * key_hex)

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

Validate X25519 key format.

Parameters
key_hexX25519 key in hex format (must not be NULL)
Returns
ASCIICHAT_OK if valid, error code on failure

Validates X25519 key format by checking hex string format. Expects 64 hex characters (32 bytes).

Note
Format validation: Checks that key is 64 hex characters (32 bytes). Validates hex character format (0-9, a-f, A-F).
Key size: X25519 keys must be exactly 64 hex characters (32 bytes). Returns error if length doesn't match or contains invalid characters.
Warning
Key format: Must be exactly 64 hex characters. Invalid characters or wrong length will fail validation.

Definition at line 227 of file keys_validation.c.

227 {
228 if (!key_hex) {
229 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters: key_hex=%p", key_hex);
230 return ERROR_INVALID_PARAM;
231 }
232
233 // Check hex string length (32 bytes = 64 hex characters)
234 size_t hex_len = strlen(key_hex);
235 if (hex_len != 64) {
236 SET_ERRNO(ERROR_CRYPTO_KEY, "X25519 key has invalid length: %zu (expected 64)", hex_len);
237 return ERROR_CRYPTO_KEY;
238 }
239
240 // Check that all characters are valid hex
241 for (size_t i = 0; i < hex_len; i++) {
242 if (!isxdigit(key_hex[i])) {
243 SET_ERRNO(ERROR_CRYPTO_KEY, "X25519 key contains invalid hex character at position %zu: '%c'", i, key_hex[i]);
244 return ERROR_CRYPTO_KEY;
245 }
246 }
247
248 return ASCIICHAT_OK;
249}

References ASCIICHAT_OK, ERROR_CRYPTO_KEY, ERROR_INVALID_PARAM, and SET_ERRNO.

Variable Documentation

◆ comment

char public_key_t::comment[MAX_COMMENT_LEN]

◆ [] [1/2]

uint8_t { ... } ::ed25519[ED25519_PRIVATE_KEY_SIZE]

Ed25519 seed (32) + public key (32) = 64 bytes

Definition at line 104 of file key_types.h.

◆ ed25519 [2/2]

◆ gpg_keygrip

char private_key_t::gpg_keygrip[MAX_GPG_KEYGRIP_LEN]

GPG keygrip (40 hex chars + null) for gpg-agent signing

Definition at line 111 of file key_types.h.

Referenced by ed25519_sign_message(), and parse_private_key().

◆ [union] [1/2]

◆ key [2/2]

◆ key_comment

char private_key_t::key_comment[MAX_COMMENT_LEN]

SSH key comment (for agent identification)

Definition at line 110 of file key_types.h.

Referenced by ed25519_sign_message(), parse_private_key(), and validate_private_key().

◆ public_key

◆ type [1/2]

◆ type [2/2]

◆ use_gpg_agent

bool private_key_t::use_gpg_agent

If true, use GPG agent for signing (currently disabled)

Definition at line 108 of file key_types.h.

Referenced by browser_client_parse_ssh_private_key(), client_parse_ssh_private_key(), ed25519_sign_message(), and parse_private_key().

◆ use_ssh_agent

bool private_key_t::use_ssh_agent

If true, use SSH agent for signing (key stays in agent)

Definition at line 107 of file key_types.h.

Referenced by browser_client_parse_ssh_private_key(), client_parse_ssh_private_key(), ed25519_sign_message(), and parse_private_key().

◆ [] [1/2]

uint8_t { ... } ::x25519[X25519_KEY_SIZE]

X25519 private key (32 bytes)

Definition at line 105 of file key_types.h.

◆ x25519 [2/2]

uint8_t private_key_t::x25519[X25519_KEY_SIZE]

X25519 private key (32 bytes)

Definition at line 105 of file key_types.h.

Referenced by private_key_to_x25519().