Files
cproof/src/omemo/crypto.c
Jabber Developer 72f4f186da
All checks were successful
CI Code / Check spelling (push) Successful in 18s
CI Code / Check coding style (push) Successful in 34s
CI Code / Code Coverage (push) Successful in 2m36s
CI Code / Linux (debian) (push) Successful in 4m41s
CI Code / Linux (ubuntu) (push) Successful in 4m52s
CI Code / Linux (arch) (push) Successful in 5m40s
merge: sync upstream profanity-im/profanity
Sync with upstream profanity-im/profanity.

Major upstream changes incorporated:

Memory management
  - Replace malloc+memset with g_new0 throughout codebase
  - Adopt auto_gchar / auto_gcharv / auto_gerror / auto_jid cleanup macros
  - Replace free() with g_free() for GAlloc'd memory

Editor rewrite
  - Remove pthread-based async editor; use GChildWatch callback API
  - New launch_editor(initial_content, callback, user_data) interface
  - Proper signal handling (SIGINT, SIGTSTP, SIGPIPE reset in child)
  - ui_suspend()/ui_resume() integration for TTY management

OMEMO improvements
  - Dual backend support: libsignal-protocol-c and libomemo-c
  - Proper pre-key removal after use (XEP-0384 compliance)
  - Automatic pre-key regeneration when store drops below threshold
  - New functions: omemo_is_device_active(), omemo_is_jid_trusted()
  - omemo_get_jid_untrusted_fingerprints() for better error messages
  - Fingerprint notifications on new device identity discovery
  - Deterministic pre-key ID generation tracking max_pre_key_id
  - omemo_trust_changed() UI updates on trust state changes

JID validation
  - RFC 6122-compliant validation in jid_is_valid()
  - Character-level checks (RFC 6122 forbidden chars: & ' / : < > @)
  - Length limits: 1023 per component, 3071 total
  - New jid_is_valid_user_jid() for user vs. service JID distinction

Database
  - Schema migration v3: UNIQUE constraint on archive_id for deduplication
  - Triggers for corrected message tracking (replaces_db_id / replaced_by_db_id)
  - db_history_result_t return type, _truncate_datetime_suffix()

UI / console
  - win_warn_needed() / win_warn_sent() warning deduplication hash table
  - PAD_MIN_HEIGHT dynamic pad sizing with PAD_THRESHOLD auto-cleanup
  - Spellcheck integration in input field with Unicode word detection
  - cons_spellcheck_setting() for /settings ui output
  - /[command]? shortcut for command help

Account config
  - Account name sanitization for GKeyFile special chars ([ ] = # \n \r)
  - Replace popen() with g_spawn_sync() for eval_password
  - TLS policy: add "direct" option alongside legacy

Connection
  - Port validation with g_assert (0–65535)
  - SHA-256 certificate fingerprint support (XMPP_CERT_PUBKEY_FINGERPRINT_SHA256)
  - "direct" TLS policy alias for legacy SSL

Common utilities
  - str_xml_sanitize() for XML 1.0 illegal character removal
  - string_matches_one_of() with formatted error messages
  - valid_tls_policy_option() helper
  - prof_date_time_format_iso8601() utility
  - Improved strip_arg_quotes() with backslash unescaping
  - prof_occurrences() uses g_slist_prepend + reverse for performance

PGP / OX
  - Proper GPGME resource cleanup with goto-cleanup pattern
  - g_string_free(xmppuri) leak fix in _ox_key_lookup

CSV export
  - Use GString + g_file_set_contents instead of raw write() syscalls

Tests
  - Restructured into subdirectories: command/, config/, xmpp/, ui/, omemo/, otr/, pgp/
  - New test_cmd_ac.c for autocompleter unit tests
  - Updated stubs for new UI suspend/resume functions

License headers
  - Migrate to SPDX-3.0 identifiers (GPL-3.0-or-later WITH OpenSSL-exception)

────────────────────────────────────────────────────
cproof-specific preservations:

  - XEP-0308 LMC: replace_id ?: id logic in message/stanza/omemo
  - Force encryption: cmd_force_encryption, test_forced_encryption
  - CWE-134: format string protection (cons_show("%s", ...))
  - y_start_pos-based paging in window.c
  - db_history_result_t return type, _truncate_datetime_suffix()

Merge-time fixes:

  - common.c: format-security (-Werror) — cons_show(errmsg) → cons_show("%s", errmsg)
  - database.c: null-deref guard — !msg->timestamp → msg && !msg->timestamp
  - console.c: implicit size_t → int cast — (int)(maxlen + 1)
  - tlscerts.c: %d for size_t — %zu

Build system:
  - Kept autotools (Makefile.am, configure.ac); upstream uses Meson
  - Restored deleted files: bootstrap.sh, autogen.sh, ax_valgrind_check.m4, configure-debug
  - Updated Makefile.am test paths for subdirectory structure
  - Added test_cmd_ac, test_forced_encryption to test sources

Functional tests:
  - Use cproof version; upstream requires stbbr_for_xmlns from updated stabber
  - Not yet available in devs/stabber fork

Closes #64

Merge author: jabber.developer2
Commits authors:
 Michael Vetter <jubalh@iodoru.org>
& Steffen Jaeckel <s@jaeckel.eu>
2026-05-26 17:48:14 +00:00

488 lines
12 KiB
C

/*
* crypto.c
* vim: expandtab:ts=4:sts=4:sw=4
*
* Copyright (C) 2019 Paul Fariello <paul@fariello.eu>
*
* SPDX-License-Identifier: GPL-3.0-or-later WITH OpenSSL-exception
*/
#include "config.h"
#include <assert.h>
#ifdef HAVE_LIBOMEMO_C
#include <omemo/signal_protocol.h>
#include <omemo/signal_protocol_types.h>
#else
#include <signal/signal_protocol.h>
#include <signal/signal_protocol_types.h>
#endif
#include "log.h"
#include "omemo/omemo.h"
#include "omemo/crypto.h"
#define AES256_GCM_TAG_LENGTH 16
#define AES256_GCM_BUFFER_SIZE 1024
int
omemo_crypto_init(void)
{
if (!gcry_check_version(GCRYPT_VERSION)) {
return GPG_ERR_UNKNOWN_VERSION;
}
gcry_error_t ret;
ret = gcry_control(GCRYCTL_SUSPEND_SECMEM_WARN);
if (ret != 0)
return ret;
ret = gcry_control(GCRYCTL_INIT_SECMEM, 16384, 0);
if (ret != 0)
return ret;
ret = gcry_control(GCRYCTL_RESUME_SECMEM_WARN);
if (ret != 0)
return ret;
ret = gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
if (ret != 0)
return ret;
/* Ask for a first random buffer to ensure CSPRNG is initialized.
* Thus we control the memleak produced by gcrypt initialization and we can
* suppress it without having false negatives */
gcry_free(gcry_random_bytes_secure(1, GCRY_VERY_STRONG_RANDOM));
return 0;
}
int
omemo_random_func(uint8_t* data, size_t len, void* user_data)
{
gcry_randomize(data, len, GCRY_VERY_STRONG_RANDOM);
return 0;
}
int
omemo_hmac_sha256_init_func(void** hmac_context, const uint8_t* key, size_t key_len, void* user_data)
{
gcry_error_t res;
gcry_mac_hd_t hd;
res = gcry_mac_open(&hd, GCRY_MAC_HMAC_SHA256, 0, NULL);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
*hmac_context = hd;
res = gcry_mac_setkey(hd, key, key_len);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
return 0;
}
int
omemo_hmac_sha256_update_func(void* hmac_context, const uint8_t* data, size_t data_len, void* user_data)
{
gcry_error_t res;
res = gcry_mac_write(hmac_context, data, data_len);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
return 0;
}
int
omemo_hmac_sha256_final_func(void* hmac_context, signal_buffer** output, void* user_data)
{
gcry_error_t res;
size_t mac_len = 32;
unsigned char out[mac_len];
res = gcry_mac_read(hmac_context, out, &mac_len);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
*output = signal_buffer_create(out, mac_len);
return 0;
}
void
omemo_hmac_sha256_cleanup_func(void* hmac_context, void* user_data)
{
gcry_mac_close(hmac_context);
}
int
omemo_sha512_digest_init_func(void** digest_context, void* user_data)
{
gcry_error_t res;
gcry_md_hd_t hd;
res = gcry_md_open(&hd, GCRY_MD_SHA512, 0);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
*digest_context = hd;
return 0;
}
int
omemo_sha512_digest_update_func(void* digest_context, const uint8_t* data, size_t data_len, void* user_data)
{
gcry_md_write(digest_context, data, data_len);
return 0;
}
int
omemo_sha512_digest_final_func(void* digest_context, signal_buffer** output, void* user_data)
{
gcry_error_t res;
unsigned char out[64];
res = gcry_md_extract(digest_context, GCRY_MD_SHA512, out, 64);
if (res != GPG_ERR_NO_ERROR) {
log_error("OMEMO: %s", gcry_strerror(res));
return OMEMO_ERR_GCRYPT;
}
*output = signal_buffer_create(out, 64);
return 0;
}
void
omemo_sha512_digest_cleanup_func(void* digest_context, void* user_data)
{
gcry_md_close(digest_context);
}
int
omemo_encrypt_func(signal_buffer** output, int cipher, const uint8_t* key, size_t key_len, const uint8_t* iv, size_t iv_len,
const uint8_t* plaintext, size_t plaintext_len, void* user_data)
{
gcry_cipher_hd_t hd;
unsigned char* padded_plaintext;
unsigned char* ciphertext;
size_t ciphertext_len;
int mode;
int algo;
uint8_t padding = 0;
switch (key_len) {
case 32:
algo = GCRY_CIPHER_AES256;
break;
default:
return OMEMO_ERR_UNSUPPORTED_CRYPTO;
}
switch (cipher) {
case SG_CIPHER_AES_CBC_PKCS5:
mode = GCRY_CIPHER_MODE_CBC;
break;
default:
return OMEMO_ERR_UNSUPPORTED_CRYPTO;
}
gcry_cipher_open(&hd, algo, mode, GCRY_CIPHER_SECURE);
gcry_cipher_setkey(hd, key, key_len);
switch (cipher) {
case SG_CIPHER_AES_CBC_PKCS5:
gcry_cipher_setiv(hd, iv, iv_len);
padding = 16 - (plaintext_len % 16);
break;
default:
assert(FALSE);
}
padded_plaintext = malloc(plaintext_len + padding);
memcpy(padded_plaintext, plaintext, plaintext_len);
memset(padded_plaintext + plaintext_len, padding, padding);
ciphertext_len = plaintext_len + padding;
ciphertext = malloc(ciphertext_len);
gcry_cipher_encrypt(hd, ciphertext, ciphertext_len, padded_plaintext, plaintext_len + padding);
*output = signal_buffer_create(ciphertext, ciphertext_len);
free(padded_plaintext);
free(ciphertext);
gcry_cipher_close(hd);
return SG_SUCCESS;
}
int
omemo_decrypt_func(signal_buffer** output, int cipher, const uint8_t* key, size_t key_len, const uint8_t* iv, size_t iv_len,
const uint8_t* ciphertext, size_t ciphertext_len, void* user_data)
{
int ret = SG_SUCCESS;
gcry_cipher_hd_t hd;
unsigned char* plaintext = NULL;
size_t plaintext_len;
int mode;
int algo;
uint8_t padding = 0;
switch (key_len) {
case 32:
algo = GCRY_CIPHER_AES256;
break;
default:
return OMEMO_ERR_UNSUPPORTED_CRYPTO;
}
switch (cipher) {
case SG_CIPHER_AES_CBC_PKCS5:
mode = GCRY_CIPHER_MODE_CBC;
break;
default:
return OMEMO_ERR_UNSUPPORTED_CRYPTO;
}
gcry_cipher_open(&hd, algo, mode, GCRY_CIPHER_SECURE);
gcry_cipher_setkey(hd, key, key_len);
switch (cipher) {
case SG_CIPHER_AES_CBC_PKCS5:
gcry_cipher_setiv(hd, iv, iv_len);
break;
default:
assert(FALSE);
}
plaintext_len = ciphertext_len;
// PKCS#5/PKCS#7 padding requires at least one byte of plaintext;
// reject malformed empty ciphertext before any plaintext[len - 1]
// access could underflow / read out-of-bounds.
if (plaintext_len == 0) {
ret = SG_ERR_INVAL;
goto out;
}
plaintext = malloc(plaintext_len);
gcry_cipher_decrypt(hd, plaintext, plaintext_len, ciphertext, ciphertext_len);
switch (cipher) {
case SG_CIPHER_AES_CBC_PKCS5:
padding = plaintext[plaintext_len - 1];
break;
default:
assert(FALSE);
}
// padding byte must address bytes that exist in plaintext.
if (padding == 0 || (size_t)padding > plaintext_len) {
ret = SG_ERR_UNKNOWN;
goto out;
}
for (int i = 0; i < padding; i++) {
if (plaintext[plaintext_len - 1 - i] != padding) {
ret = SG_ERR_UNKNOWN;
goto out;
}
}
*output = signal_buffer_create(plaintext, plaintext_len - padding);
out:
free(plaintext);
gcry_cipher_close(hd);
return ret;
}
int
aes128gcm_encrypt(unsigned char* ciphertext, size_t* ciphertext_len, unsigned char* tag, size_t* tag_len, const unsigned char* const plaintext, size_t plaintext_len, const unsigned char* const iv, const unsigned char* const key)
{
gcry_error_t res;
gcry_cipher_hd_t hd;
res = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_GCM, GCRY_CIPHER_SECURE);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setkey(hd, key, AES128_GCM_KEY_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setiv(hd, iv, AES128_GCM_IV_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_encrypt(hd, ciphertext, *ciphertext_len, plaintext, plaintext_len);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_gettag(hd, tag, *tag_len);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
out:
gcry_cipher_close(hd);
return res;
}
int
aes128gcm_decrypt(unsigned char* plaintext, size_t* plaintext_len, const unsigned char* const ciphertext, size_t ciphertext_len, const unsigned char* const iv, size_t iv_len, const unsigned char* const key, const unsigned char* const tag)
{
gcry_error_t res;
gcry_cipher_hd_t hd;
res = gcry_cipher_open(&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_GCM, GCRY_CIPHER_SECURE);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setkey(hd, key, AES128_GCM_KEY_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setiv(hd, iv, iv_len);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_decrypt(hd, plaintext, *plaintext_len, ciphertext, ciphertext_len);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_checktag(hd, tag, AES128_GCM_TAG_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
out:
gcry_cipher_close(hd);
return res;
}
gcry_error_t
aes256gcm_crypt_file(FILE* in, FILE* out, off_t file_size,
unsigned char key[], unsigned char nonce[], gboolean encrypt)
{
if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) {
fputs("libgcrypt has not been initialized\n", stderr);
abort();
}
if (!encrypt) {
file_size -= AES256_GCM_TAG_LENGTH;
}
gcry_error_t res;
gcry_cipher_hd_t hd;
res = gcry_cipher_open(&hd, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_GCM,
GCRY_CIPHER_SECURE);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setkey(hd, key, OMEMO_AESGCM_KEY_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
res = gcry_cipher_setiv(hd, nonce, OMEMO_AESGCM_NONCE_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
unsigned char buffer[AES256_GCM_BUFFER_SIZE];
size_t bytes = 0;
off_t bytes_read = 0, bytes_available = 0, read_size = 0;
while (bytes_read < file_size) {
bytes_available = file_size - bytes_read;
if (!bytes_available || ferror(in) != 0) {
break;
}
if (bytes_available < AES256_GCM_BUFFER_SIZE) {
read_size = bytes_available;
gcry_cipher_final(hd); // Signal last round of bytes.
} else {
read_size = AES256_GCM_BUFFER_SIZE;
}
bytes = fread(buffer, 1, (size_t)read_size, in);
bytes_read += (off_t)bytes;
if (encrypt) {
res = gcry_cipher_encrypt(hd, buffer, bytes, NULL, 0);
} else {
res = gcry_cipher_decrypt(hd, buffer, bytes, NULL, 0);
}
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
fwrite(buffer, 1, bytes, out);
}
unsigned char tag[AES256_GCM_TAG_LENGTH];
if (encrypt) {
// Append authentication tag at the end of the file.
res = gcry_cipher_gettag(hd, tag, AES256_GCM_TAG_LENGTH);
if (res != GPG_ERR_NO_ERROR) {
goto out;
}
fwrite(tag, 1, AES256_GCM_TAG_LENGTH, out);
} else {
// Read and verify authentication tag stored at the end of the file.
bytes = fread(tag, 1, AES256_GCM_TAG_LENGTH, in);
res = gcry_cipher_checktag(hd, tag, bytes);
}
out:
gcry_cipher_close(hd);
return res;
}
char*
aes256gcm_create_secure_fragment(unsigned char* key, unsigned char* nonce)
{
int key_size = OMEMO_AESGCM_KEY_LENGTH;
int nonce_size = OMEMO_AESGCM_NONCE_LENGTH;
char* fragment = gcry_malloc_secure((nonce_size + key_size) * 2 + 1);
for (int i = 0; i < nonce_size; i++) {
sprintf(&(fragment[i * 2]), "%02x", nonce[i]);
}
for (int i = 0; i < key_size; i++) {
sprintf(&(fragment[(i + nonce_size) * 2]), "%02x", key[i]);
}
return fragment;
}