Files
cproof/src/pgp/ox.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

593 lines
17 KiB
C

/*
* ox.c
* vim: expandtab:ts=4:sts=4:sw=4
*
* Copyright (C) 2020 Stefan Kropp <stefan@debxwoody.de>
* Copyright (C) 2020 - 2026 Michael Vetter <jubalh@iodoru.org>
*
* SPDX-License-Identifier: GPL-3.0-or-later WITH OpenSSL-exception
*/
#include "config.h"
#include <locale.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <gpgme.h>
#include "log.h"
#include "common.h"
#include "pgp/ox.h"
#include "config/files.h"
#include "ui/ui.h"
static gpgme_key_t _ox_key_lookup(const char* const barejid, gboolean secret_only);
static gboolean _ox_key_is_usable(gpgme_key_t key, const char* const barejid, gboolean secret);
/*!
* \brief Public keys with XMPP-URI.
*
* This function will look for all public key with a XMPP-URI as UID.
*
* @returns GHashTable* with GString* xmpp-uri and ProfPGPKey* value. Empty
* hash, if there is no key. NULL in case of error.
*
*/
GHashTable*
ox_gpg_public_keys(void)
{
gpgme_error_t error;
GHashTable* result = g_hash_table_new_full(g_str_hash, g_str_equal, free, (GDestroyNotify)p_gpg_free_key);
gpgme_ctx_t ctx;
error = gpgme_new(&ctx);
if (error) {
log_error("OX: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
return NULL;
}
error = gpgme_op_keylist_start(ctx, NULL, 0); // all public keys
if (error == GPG_ERR_NO_ERROR) {
gpgme_key_t key;
error = gpgme_op_keylist_next(ctx, &key);
if (error != GPG_ERR_EOF && error != GPG_ERR_NO_ERROR) {
log_error("OX: gpgme_op_keylist_next %s %s", gpgme_strsource(error), gpgme_strerror(error));
g_hash_table_destroy(result);
gpgme_release(ctx);
return NULL;
}
while (!error) {
// Looking for XMPP URI UID
gpgme_user_id_t uid = key->uids;
gpgme_user_id_t xmppid = NULL;
while (!xmppid && uid) {
if (uid->name && strlen(uid->name) >= 10) {
if (strstr(uid->name, "xmpp:") == uid->name) {
xmppid = uid;
}
}
uid = uid->next;
}
if (xmppid) {
// Build Key information about all subkey
gpgme_subkey_t sub = key->subkeys;
ProfPGPKey* p_pgpkey = p_gpg_key_new();
p_pgpkey->id = strdup(sub->keyid);
p_pgpkey->name = strdup(xmppid->uid);
p_pgpkey->fp = strdup(sub->fpr);
if (sub->can_encrypt)
p_pgpkey->encrypt = TRUE;
if (sub->can_authenticate)
p_pgpkey->authenticate = TRUE;
if (sub->can_certify)
p_pgpkey->certify = TRUE;
if (sub->can_sign)
p_pgpkey->sign = TRUE;
sub = sub->next;
while (sub) {
if (sub->can_encrypt)
p_pgpkey->encrypt = TRUE;
if (sub->can_authenticate)
p_pgpkey->authenticate = TRUE;
if (sub->can_certify)
p_pgpkey->certify = TRUE;
if (sub->can_sign)
p_pgpkey->sign = TRUE;
sub = sub->next;
}
g_hash_table_insert(result, strdup(p_pgpkey->name), p_pgpkey);
}
gpgme_key_unref(key);
error = gpgme_op_keylist_next(ctx, &key);
}
}
gpgme_release(ctx);
return result;
}
char*
p_ox_gpg_signcrypt(const char* const sender_barejid, const char* const recipient_barejid, const char* const message)
{
char* result = NULL;
gpgme_ctx_t ctx = NULL;
gpgme_key_t recp[3] = { NULL, NULL, NULL };
gpgme_data_t plain = NULL;
gpgme_data_t cipher = NULL;
char* cipher_str = NULL;
setlocale(LC_ALL, "");
gpgme_check_version(NULL);
gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
gpgme_error_t error = gpgme_new(&ctx);
if (GPG_ERR_NO_ERROR != error) {
log_error("OX: Failed to create gpgme context. %s %s", gpgme_strsource(error), gpgme_strerror(error));
return NULL;
}
error = gpgme_set_protocol(ctx, GPGME_PROTOCOL_OPENPGP);
if (error != 0) {
log_error("OX: Signcrypt error: %s", gpgme_strerror(error));
}
gpgme_set_armor(ctx, 0);
gpgme_set_textmode(ctx, 0);
gpgme_set_offline(ctx, 1);
gpgme_set_keylist_mode(ctx, GPGME_KEYLIST_MODE_LOCAL);
char* xmpp_jid_me = alloca((strlen(sender_barejid) + 6) * sizeof(char));
char* xmpp_jid_recipient = alloca((strlen(recipient_barejid) + 6) * sizeof(char));
strcpy(xmpp_jid_me, "xmpp:");
strcpy(xmpp_jid_recipient, "xmpp:");
strcat(xmpp_jid_me, sender_barejid);
strcat(xmpp_jid_recipient, recipient_barejid);
gpgme_signers_clear(ctx);
// lookup own key
recp[0] = _ox_key_lookup(sender_barejid, TRUE);
if (recp[0] == NULL) {
cons_show_error("Can't find OX key for %s", xmpp_jid_me);
log_error("OX: Key not found for %s.", xmpp_jid_me);
goto cleanup;
}
error = gpgme_signers_add(ctx, recp[0]);
if (error != 0) {
log_error("OX: gpgme_signers_add %s. Error: %s", xmpp_jid_me, gpgme_strerror(error));
goto cleanup;
}
// lookup key of recipient
recp[1] = _ox_key_lookup(recipient_barejid, FALSE);
if (recp[1] == NULL) {
cons_show_error("Can't find OX key for %s", xmpp_jid_recipient);
log_error("OX: Key not found for %s.", xmpp_jid_recipient);
goto cleanup;
}
recp[2] = NULL;
if (recp[0]->uids) {
log_debug("OX: %s <%s>", recp[0]->uids->name, recp[0]->uids->email);
}
if (recp[1]->uids) {
log_debug("OX: %s <%s>", recp[1]->uids->name, recp[1]->uids->email);
}
gpgme_encrypt_flags_t flags = 0;
error = gpgme_data_new_from_mem(&plain, message, strlen(message), 0);
if (error != 0) {
log_error("OX: %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_data_new(&cipher);
if (error != 0) {
log_error("OX: %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_op_encrypt_sign(ctx, recp, flags, plain, cipher);
if (error != 0) {
log_error("OX: %s", gpgme_strerror(error));
goto cleanup;
}
size_t len;
cipher_str = gpgme_data_release_and_get_mem(cipher, &len);
cipher = NULL; // Already released by gpgme_data_release_and_get_mem
result = g_base64_encode((unsigned char*)cipher_str, len);
cleanup:
if (cipher_str)
gpgme_free(cipher_str);
if (plain)
gpgme_data_release(plain);
if (cipher)
gpgme_data_release(cipher);
if (recp[0])
gpgme_key_release(recp[0]);
if (recp[1])
gpgme_key_release(recp[1]);
if (ctx)
gpgme_release(ctx);
return result;
}
gboolean
ox_is_private_key_available(const char* const barejid)
{
g_assert(barejid);
gboolean result = FALSE;
gpgme_key_t key = _ox_key_lookup(barejid, TRUE);
if (key) {
if (_ox_key_is_usable(key, barejid, TRUE)) {
result = TRUE;
}
gpgme_key_unref(key);
}
return result;
}
gboolean
ox_is_public_key_available(const char* const barejid)
{
g_assert(barejid);
gboolean result = FALSE;
gpgme_key_t key = _ox_key_lookup(barejid, FALSE);
if (key) {
if (_ox_key_is_usable(key, barejid, FALSE)) {
result = TRUE;
}
gpgme_key_unref(key);
}
return result;
}
static gpgme_key_t
_ox_key_lookup(const char* const barejid, gboolean secret_only)
{
g_assert(barejid);
log_debug("OX: Looking for %s key: %s", secret_only == TRUE ? "Private" : "Public", barejid);
gpgme_key_t key = NULL;
gpgme_error_t error;
gpgme_ctx_t ctx;
error = gpgme_new(&ctx);
if (error) {
log_error("OX: gpgme_new failed: %s %s", gpgme_strsource(error), gpgme_strerror(error));
return NULL;
}
error = gpgme_op_keylist_start(ctx, NULL, secret_only);
if (error == GPG_ERR_NO_ERROR) {
error = gpgme_op_keylist_next(ctx, &key);
if (error != GPG_ERR_EOF && error != GPG_ERR_NO_ERROR) {
log_error("OX: gpgme_op_keylist_next %s %s", gpgme_strsource(error), gpgme_strerror(error));
return NULL;
}
GString* xmppuri = g_string_new("xmpp:");
g_string_append(xmppuri, barejid);
while (!error) {
// Looking for XMPP URI UID
gpgme_user_id_t uid = key->uids;
while (uid) {
if (uid->name && strlen(uid->name) >= 10) {
if (g_strcmp0(uid->name, xmppuri->str) == 0) {
gpgme_release(ctx);
g_string_free(xmppuri, TRUE);
return key;
}
}
uid = uid->next;
}
gpgme_key_unref(key);
error = gpgme_op_keylist_next(ctx, &key);
}
g_string_free(xmppuri, TRUE);
}
gpgme_release(ctx);
return key;
}
static gboolean
_ox_key_is_usable(gpgme_key_t key, const char* const barejid, gboolean secret)
{
gboolean result = TRUE;
if (key->revoked || key->expired || key->disabled) {
cons_show_error("%s's key is revoked, expired or disabled", barejid);
log_info("OX: %s's key is revoked, expired or disabled", barejid);
result = FALSE;
}
// This might be a nice features but AFAIK is not defined in the XEP.
// If we add this we need to expand our documentation on how to set the
// trust leven in gpg. I'll add an example to this commit body.
/*
if (key->owner_trust < GPGME_VALIDITY_MARGINAL) {
cons_show_error(" %s's key is has a trust level lower than marginal", barejid);
log_info("OX: Owner trust of %s's key is < GPGME_VALIDITY_MARGINAL", barejid);
result = FALSE;
}
*/
return result;
}
/*!
* @brief XMPP-OX: Decrypt OX Message.
*
* @param base64 base64_encode OpenPGP message.
*
* @result decrypt XMPP OX Message NULL terminated C-String
*/
char*
p_ox_gpg_decrypt(char* base64)
{
char* result = NULL;
gpgme_ctx_t ctx = NULL;
gpgme_data_t plain = NULL;
gpgme_data_t cipher = NULL;
guchar* encrypted = NULL;
char* plain_str = NULL;
// if there is no private key avaibale,
// we don't try do decrypt
if (!ox_is_private_key_available(connection_get_barejid())) {
return NULL;
}
setlocale(LC_ALL, "");
gpgme_check_version(NULL);
gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
gpgme_error_t error = gpgme_new(&ctx);
if (GPG_ERR_NO_ERROR != error) {
log_error("OX: gpgme_new failed: %s %s", gpgme_strsource(error), gpgme_strerror(error));
return NULL;
}
error = gpgme_set_protocol(ctx, GPGME_PROTOCOL_OPENPGP);
if (error != 0) {
log_error("OX: %s", gpgme_strerror(error));
}
gpgme_set_armor(ctx, 0);
gpgme_set_textmode(ctx, 0);
gpgme_set_offline(ctx, 1);
gpgme_set_keylist_mode(ctx, GPGME_KEYLIST_MODE_LOCAL);
gsize s;
encrypted = g_base64_decode(base64, &s);
error = gpgme_data_new_from_mem(&cipher, (char*)encrypted, s, 0);
if (error != 0) {
log_error("OX: gpgme_data_new_from_mem: %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_data_new(&plain);
if (error != 0) {
log_error("OX: %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_op_decrypt_verify(ctx, cipher, plain);
if (error != 0) {
log_error("OX: gpgme_op_decrypt: %s", gpgme_strerror(error));
error = gpgme_op_decrypt(ctx, cipher, plain);
if (error != 0) {
goto cleanup;
}
}
size_t len;
plain_str = gpgme_data_release_and_get_mem(plain, &len);
plain = NULL; // Already released by gpgme_data_release_and_get_mem
if (plain_str) {
result = strndup(plain_str, len);
}
cleanup:
if (encrypted)
g_free(encrypted);
if (plain_str)
gpgme_free(plain_str);
if (plain)
gpgme_data_release(plain);
if (cipher)
gpgme_data_release(cipher);
if (ctx)
gpgme_release(ctx);
return result;
}
/*!
* \brief Read public key from file.
*
* This function is used the read a public key from a file.
*
* This function is used to read a key and push it on PEP. There are some checks
* in this function:
*
* Key is not
* - gkey->revoked
* - gkey->expired
* - gkey->disabled
* - gkey->invalid
* - gkey->secret
*
* Only one key in the file.
*
* \param filename filename to read the file.
* \param key result with base64 encode key or NULL
* \param fp result with the fingerprint or NULL
*
*/
void
p_ox_gpg_readkey(const char* const filename, char** key, char** fp)
{
log_info("PX: Read OpenPGP Key from file %s", filename);
GError* gerr = NULL;
gchar* data = NULL;
gsize size = -1;
gpgme_ctx_t ctx = NULL;
gpgme_data_t gpgme_data = NULL;
gpgme_key_t gkey = NULL;
gpgme_key_t end = NULL;
gboolean success = g_file_get_contents(filename,
&data,
&size,
&gerr);
if (success) {
setlocale(LC_ALL, "");
gpgme_check_version(NULL);
gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
gpgme_error_t error = gpgme_new(&ctx);
if (GPG_ERR_NO_ERROR != error) {
log_error("OX: Read OpenPGP key from file: gpgme_new failed: %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_set_protocol(ctx, GPGME_PROTOCOL_OPENPGP);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: set GPGME_PROTOCOL_OPENPGP: %s", gpgme_strerror(error));
goto cleanup;
}
gpgme_set_armor(ctx, 0);
gpgme_set_textmode(ctx, 0);
gpgme_set_offline(ctx, 1);
gpgme_set_keylist_mode(ctx, GPGME_KEYLIST_MODE_LOCAL);
error = gpgme_data_new_from_mem(&gpgme_data, (char*)data, size, 0);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: gpgme_data_new_from_mem %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_op_keylist_from_data_start(ctx, gpgme_data, 0);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: gpgme_op_keylist_from_data_start %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_op_keylist_next(ctx, &gkey);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: gpgme_op_keylist_next %s", gpgme_strerror(error));
goto cleanup;
}
error = gpgme_op_keylist_next(ctx, &end);
if (error == GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: ambiguous key");
goto cleanup;
}
if (gkey->revoked || gkey->expired || gkey->disabled || gkey->invalid || gkey->secret) {
log_error("OX: Read OpenPGP key from file: Key is not valid");
goto cleanup;
}
gchar* keybase64 = g_base64_encode((const guchar*)data, size);
*key = strdup(keybase64);
*fp = strdup(gkey->fpr);
g_free(keybase64);
} else {
log_error("OX: Read OpenPGP key from file: Unable to read file: %s", gerr->message);
g_error_free(gerr);
}
cleanup:
if (data)
g_free(data);
if (gpgme_data)
gpgme_data_release(gpgme_data);
if (gkey)
gpgme_key_unref(gkey);
if (end)
gpgme_key_unref(end);
if (ctx)
gpgme_release(ctx);
}
gboolean
p_ox_gpg_import(char* base64_public_key)
{
gsize size = -1;
guchar* key = g_base64_decode(base64_public_key, &size);
gboolean result = TRUE;
setlocale(LC_ALL, "");
gpgme_check_version(NULL);
gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
gpgme_ctx_t ctx = NULL;
gpgme_data_t gpgme_data = NULL;
gpgme_error_t error = gpgme_new(&ctx);
if (GPG_ERR_NO_ERROR != error) {
log_error("OX: Read OpenPGP key from file: gpgme_new failed: %s", gpgme_strerror(error));
result = FALSE;
goto cleanup;
}
error = gpgme_set_protocol(ctx, GPGME_PROTOCOL_OPENPGP);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: set GPGME_PROTOCOL_OPENPGP: %s", gpgme_strerror(error));
result = FALSE;
goto cleanup;
}
gpgme_set_armor(ctx, 0);
gpgme_set_textmode(ctx, 0);
gpgme_set_offline(ctx, 1);
gpgme_set_keylist_mode(ctx, GPGME_KEYLIST_MODE_LOCAL);
error = gpgme_data_new_from_mem(&gpgme_data, (gchar*)key, size, 0);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Read OpenPGP key from file: gpgme_data_new_from_mem %s", gpgme_strerror(error));
result = FALSE;
goto cleanup;
}
error = gpgme_op_import(ctx, gpgme_data);
if (error != GPG_ERR_NO_ERROR) {
log_error("OX: Failed to import key");
result = FALSE;
}
cleanup:
if (key)
g_free(key);
if (gpgme_data)
gpgme_data_release(gpgme_data);
if (ctx)
gpgme_release(ctx);
return result;
}