// gpgme supplies OpenPGP cryptography; policy and result ownership stay in V. // SPDX-License-Identifier: GPL-2.0-or-later module engine import os import sync import time #flag -lgpgme #flag -lgpg-error #include #include struct C.gpgme_context {} struct C.gpgme_data {} struct C._gpgme_subkey { next &C._gpgme_subkey fpr &char keyid &char timestamp uint expires uint length u32 revoked u32 } struct C._gpgme_user_id { uid &char name &char email &char } struct C._gpgme_key { subkeys &C._gpgme_subkey uids &C._gpgme_user_id disabled u32 expired u32 owner_trust i32 } struct C._gpgme_signature { next &C._gpgme_signature fpr &char status u32 validity i32 summary u32 timestamp uint exp_timestamp uint validity_reason u32 } struct C._gpgme_op_verify_result { signatures &C._gpgme_signature } fn C.gpgme_check_version(&char) &char fn C.gpgme_engine_check_version(i32) u32 fn C.gpgme_new(&&C.gpgme_context) u32 fn C.gpgme_release(&C.gpgme_context) fn C.gpgme_set_protocol(&C.gpgme_context, i32) u32 fn C.gpgme_ctx_set_engine_info(&C.gpgme_context, i32, &char, &char) u32 fn C.gpgme_set_locale(&C.gpgme_context, i32, &char) u32 fn C.gpgme_strerror(u32) &char fn C.gpgme_data_new_from_fd(&&C.gpgme_data, i32) u32 fn C.gpgme_data_new_from_mem(&&C.gpgme_data, &char, uint, i32) u32 fn C.gpgme_data_release(&C.gpgme_data) fn C.gpgme_op_verify(&C.gpgme_context, &C.gpgme_data, &C.gpgme_data, &C.gpgme_data) u32 fn C.gpgme_op_verify_result(&C.gpgme_context) &C._gpgme_op_verify_result fn C.gpgme_get_key(&C.gpgme_context, &char, &&C._gpgme_key, i32) u32 fn C.gpgme_key_unref(&C._gpgme_key) fn C.gpgme_get_keylist_mode(&C.gpgme_context) u32 fn C.gpgme_set_keylist_mode(&C.gpgme_context, u32) u32 fn C.gpgme_op_import_keys(&C.gpgme_context, &&C._gpgme_key) u32 fn C.gpgme_op_import_result(&C.gpgme_context) &C._gpgme_op_import_result struct C._gpgme_import_status { result u32 } struct C._gpgme_op_import_result { considered i32 imports &C._gpgme_import_status } struct C._gpgme_engine_info { next &C._gpgme_engine_info protocol i32 file_name &char home_dir &char } fn C.gpgme_get_engine_info(&&C._gpgme_engine_info) u32 fn C.setlocale(i32, &char) &char const gpgme_initialization = sync.new_mutex() fn gpg_error_code(status u32) u32 { return status & 0xffff } fn (mut handle Handle) check_gpg_error(status u32) ! { if gpg_error_code(status) != 0 { return handle.fail(.gpgme, unsafe { cstring_to_vstring(C.gpgme_strerror(status)) }) } } fn signature_library_version() ?string { mut initialization := gpgme_initialization initialization.@lock() defer { initialization.unlock() } version := C.gpgme_check_version(unsafe { nil }) if version == unsafe { nil } { return none } return gpg_string(version) } fn (mut handle Handle) check_initial_keyring(home string) { legacy := home + 'pubring.gpg' modern := home + 'pubring.kbx' // modern GnuPG keyboxes are valid public keyrings when no legacy ring exists. public_ring := if !os.exists(legacy) && os.exists(modern) { modern } else { legacy } if !handle.package_readable(public_ring) || !handle.package_readable(home + 'trustdb.gpg') { handle.last_error = .not_a_file handle.last_detail_valid = false handle.log(.debug, 'Signature verification will fail!\n') handle.log(.warning, "Public keyring not found; have you run 'pacman-key --init'?\n") } } fn signature_log_string(pointer &char) string { return if pointer == unsafe { nil } { '(null)' } else { gpg_string(pointer) } } fn (mut handle Handle) initialize_signatures() ! { if handle.signature_initialized { return } home := handle.opts.strings[.gpgdir] handle.check_initial_keyring(home) version := signature_library_version() or { return handle.fail(.gpgme, 'GPGME initialization failed') } // callbacks may verify another handle; never call them under the global setup mutex. handle.log(.debug, 'GPGME version: ${version}\n') mut initialization := gpgme_initialization initialization.@lock() mut held := true defer { if held { initialization.unlock() } } handle.check_gpg_error(C.gpgme_engine_check_version(C.GPGME_PROTOCOL_OpenPGP))! mut info := &C._gpgme_engine_info(unsafe { nil }) handle.check_gpg_error(C.gpgme_get_engine_info(&info))! file := if info == unsafe { nil } { '(null)' } else { signature_log_string(info.file_name) } directory := if home == '' { '(null)' } else { home } held = false initialization.unlock() // initialization survives a later context allocation failure, as in signing.c. handle.signature_initialized = true handle.log(.debug, 'GPGME engine info: file=${file}, home=${directory}\n') } fn (mut handle Handle) signature_context() !&C.gpgme_context { return handle.signature_context_for_path(none) } fn (mut handle Handle) signature_context_for_path(path ?string) !&C.gpgme_context { handle.initialize_signatures()! if filename := path { handle.log(.debug, 'checking signature for ${filename}\n') } mut context := &C.gpgme_context(unsafe { nil }) handle.check_gpg_error(C.gpgme_new(&context))! mut ready := false defer { if !ready { C.gpgme_release(context) } } handle.check_gpg_error(C.gpgme_set_protocol(context, C.GPGME_PROTOCOL_OpenPGP))! // global engine configuration leaks the first handle's keyring into later handles. home := handle.opts.strings[.gpgdir] home_pointer := if home == '' { unsafe { &char(nil) } } else { unsafe { &char(home.str) } } handle.check_gpg_error(C.gpgme_ctx_set_engine_info(context, C.GPGME_PROTOCOL_OpenPGP, unsafe { nil }, home_pointer))! handle.check_gpg_error(C.gpgme_set_locale(context, C.LC_CTYPE, C.setlocale(C.LC_CTYPE, unsafe { nil })))! $if !windows { handle.check_gpg_error(C.gpgme_set_locale(context, C.LC_MESSAGES, C.setlocale(C.LC_MESSAGES, unsafe { nil })))! } ready = true return context } fn gpg_string(pointer &char) string { return if pointer == unsafe { nil } { '' } else { unsafe { cstring_to_vstring(pointer) } } } fn signature_status(status u32, disabled bool) SigStatus { if disabled { return .key_disabled } return match int(gpg_error_code(status)) { C.GPG_ERR_NO_ERROR { .valid } C.GPG_ERR_KEY_EXPIRED { .key_expired } C.GPG_ERR_SIG_EXPIRED { .sig_expired } C.GPG_ERR_NO_PUBKEY { .key_unknown } else { .invalid } } } fn signature_validity(validity i32) SigValidity { return match validity { C.GPGME_VALIDITY_ULTIMATE, C.GPGME_VALIDITY_FULL { .full } C.GPGME_VALIDITY_MARGINAL { .marginal } C.GPGME_VALIDITY_NEVER { .never } else { .unknown } } } fn signature_validity_name(value i32) string { return match value { C.GPGME_VALIDITY_UNKNOWN { 'unknown' } C.GPGME_VALIDITY_UNDEFINED { 'undefined' } C.GPGME_VALIDITY_NEVER { 'never' } C.GPGME_VALIDITY_MARGINAL { 'marginal' } C.GPGME_VALIDITY_FULL { 'full' } C.GPGME_VALIDITY_ULTIMATE { 'ultimate' } else { '???' } } } fn signature_summaries(value u32) []string { if value == 0 { return ['(empty)'] } bits := [u32(C.GPGME_SIGSUM_VALID), u32(C.GPGME_SIGSUM_GREEN), u32(C.GPGME_SIGSUM_RED), u32(C.GPGME_SIGSUM_KEY_REVOKED), u32(C.GPGME_SIGSUM_KEY_EXPIRED), u32(C.GPGME_SIGSUM_SIG_EXPIRED), u32(C.GPGME_SIGSUM_KEY_MISSING), u32(C.GPGME_SIGSUM_CRL_MISSING), u32(C.GPGME_SIGSUM_CRL_TOO_OLD), u32(C.GPGME_SIGSUM_BAD_POLICY), u32(C.GPGME_SIGSUM_SYS_ERROR)] labels := ['valid', 'green', 'red', 'key revoked', 'key expired', 'sig expired', 'key missing', 'crl missing', 'crl too old', 'bad policy', 'sys error'] mut values := []string{} for index, bit in bits { if value & bit != 0 { values << labels[index] } } return values } fn (handle &Handle) log_signature_result(signature &C._gpgme_signature) { fingerprint := if signature.fpr == unsafe { nil } { '(null)' } else { gpg_string(signature.fpr) } handle.log(.debug, 'fingerprint: ${fingerprint}\n') for summary in signature_summaries(signature.summary) { handle.log(.debug, 'summary: ${summary}\n') } handle.log(.debug, 'status: ${gpg_string(C.gpgme_strerror(signature.status))}\n') handle.log(.debug, 'timestamp: ${signature.timestamp}\n') if i64(signature.timestamp) > time.now().unix() { handle.log(.debug, 'signature timestamp is greater than system time.\n') } handle.log(.debug, 'exp_timestamp: ${signature.exp_timestamp}\n') handle.log(.debug, 'validity: ${signature_validity_name(signature.validity)}; reason: ${gpg_string(C.gpgme_strerror(signature.validity_reason))}\n') } fn (mut handle Handle) signature_result(context &C.gpgme_context, signature &C._gpgme_signature, retain bool) !(SigResult, voidptr) { handle.log_signature_result(signature) mut key := &C._gpgme_key(unsafe { nil }) defer { if key != unsafe { nil } { C.gpgme_key_unref(key) } } status := C.gpgme_get_key(context, signature.fpr, &key, 0) mut info := PGPKey{} mut disabled := false if gpg_error_code(status) == C.GPG_ERR_EOF { handle.log(.debug, 'key lookup failed, unknown key\n') info = PGPKey{ fingerprint: gpg_string(signature.fpr) } } else { handle.check_gpg_error(status)! if key != unsafe { nil } && key.uids != unsafe { nil } && key.subkeys != unsafe { nil } { info = PGPKey{ known: true fingerprint: gpg_string(key.subkeys.fpr) uid: gpg_string(key.uids.uid) name: gpg_string(key.uids.name) email: gpg_string(key.uids.email) created: i64(key.subkeys.timestamp) expires: i64(key.subkeys.expires) } disabled = key.disabled != 0 handle.log(.debug, 'key: ${info.fingerprint}, ${info.uid}, owner_trust ${signature_validity_name(key.owner_trust)}, disabled ${key.disabled}\n') } } data := if retain && info.known { voidptr(key) } else { unsafe { nil } } if data != unsafe { nil } { C.gpgme_key_ref(key) } return SigResult{ key: info, status: signature_status(signature.status, disabled), validity: signature_validity(signature.validity) }, data } pub fn (mut handle Handle) check_signature(filename string, embedded ?string) ![]SigResult { handle.check()! verification := handle.verify_signature(filename, embedded, false) or { handle.log_signature_error(err) return err } return verification.results } fn (mut handle Handle) verify_signature(filename string, embedded ?string, retain bool) !SignatureVerification { path := c_string_prefix(filename) if !handle.package_readable(path) { return handle.fail(.not_a_file, path) } mut signature_file := os.File{} defer { if signature_file.is_opened { signature_file.close() } } if embedded == none { sigpath := path + '.sig' if !handle.package_readable(sigpath) { handle.log(.debug, 'sig path ${sigpath} could not be opened\n') return handle.fail(.sig_missing, sigpath) } signature_file = os.open(sigpath) or { handle.log(.debug, 'sig path ${sigpath} could not be opened\n') return handle.fail(.sig_missing, err.msg()) } } mut file := os.open(path) or { return handle.fail(.not_a_file, err.msg()) } defer { file.close() } context := handle.signature_context_for_path(path)! defer { C.gpgme_release(context) } mut file_data := &C.gpgme_data(unsafe { nil }) handle.check_gpg_error(C.gpgme_data_new_from_fd(&file_data, file.fd))! defer { C.gpgme_data_release(file_data) } mut signature_data := &C.gpgme_data(unsafe { nil }) defer { if signature_data != unsafe { nil } { C.gpgme_data_release(signature_data) } } if value := embedded { decoded := decode_signature(value) or { return handle.fail(.sig_invalid, err.msg()) } // GPGME copies the data and requires a non-null pointer for an empty signature. data := if decoded.len == 0 { c'' } else { unsafe { &char(decoded.data) } } handle.check_gpg_error(C.gpgme_data_new_from_mem(&signature_data, data, uint(decoded.len), 1))! } else { handle.check_gpg_error(C.gpgme_data_new_from_fd(&signature_data, signature_file.fd))! } handle.check_gpg_error(C.gpgme_op_verify(context, signature_data, file_data, unsafe { nil }))! verification := C.gpgme_op_verify_result(context) if verification == unsafe { nil } || verification.signatures == unsafe { nil } { handle.log(.debug, 'no signatures returned\n') return handle.fail(.sig_missing, path) } mut result := []SigResult{} mut keys := []voidptr{} mut complete := false defer { if !complete { release_signature_keys(keys) } } mut count := 0 for signature := verification.signatures; signature != unsafe { nil }; signature = signature.next { count++ } handle.log(.debug, '${count} signatures returned\n') for signature := verification.signatures; signature != unsafe { nil }; signature = signature.next { value, key := handle.signature_result(context, signature, retain)! result << value if retain { keys << key } } complete = true return SignatureVerification{ results: result, key_data: keys } }