Remove orphaned keychain keys of sessions saved at logout

Keys whose snapshot no longer exists, for example because it was deleted
by a cache cleaner or because the keychain was locked when deleting it,
are deleted when saving at logout, when claiming snapshots at startup and
when removing all snapshots. This is done with the snapshot lock held, so
snapshots being saved or restored are never affected. Only keys with the
format of the ids kitty creates are deleted.
This commit is contained in:
Kovid Goyal 2026-10-16 12:02:20 +05:30
parent 8f0b7eff31
commit 7c35cc6429
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
4 changed files with 131 additions and 15 deletions

View file

@ -1528,10 +1528,11 @@ set_keychain_query_ui_fail(CFMutableDictionaryRef q) {
static CFMutableDictionaryRef
keychain_query(const char *service, const char *account) {
// account can be NULL to match all items of service
CFMutableDictionaryRef q = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFStringRef s = CFStringCreateWithCString(NULL, service, kCFStringEncodingUTF8);
CFStringRef a = CFStringCreateWithCString(NULL, account, kCFStringEncodingUTF8);
if (!q || !s || !a) {
CFStringRef a = account ? CFStringCreateWithCString(NULL, account, kCFStringEncodingUTF8) : NULL;
if (!q || !s || (account && !a)) {
if (q) CFRelease(q);
if (s) CFRelease(s);
if (a) CFRelease(a);
@ -1540,9 +1541,11 @@ keychain_query(const char *service, const char *account) {
}
CFDictionarySetValue(q, kSecClass, kSecClassGenericPassword);
CFDictionarySetValue(q, kSecAttrService, s);
CFDictionarySetValue(q, kSecAttrAccount, a);
CFRelease(s);
CFRelease(a);
if (a) {
CFDictionarySetValue(q, kSecAttrAccount, a);
CFRelease(a);
}
return q;
}
@ -1554,7 +1557,7 @@ set_keychain_error(OSStatus status, const char *action) {
CFStringGetCString(m, msg, sizeof(msg), kCFStringEncodingUTF8);
CFRelease(m);
}
PyErr_Format(PyExc_OSError, "Failed to %s the item in the keychain: %s (error code: %d)", action, msg, (int)status);
PyErr_Format(PyExc_OSError, "Failed to %s the keychain: %s (error code: %d)", action, msg, (int)status);
return NULL;
}
@ -1585,7 +1588,7 @@ cocoa_keychain_store_secret(PyObject *self UNUSED, PyObject *args) {
OSStatus status = SecItemAdd(q, NULL);
restore_keychain_interaction(ki);
CFRelease(q);
if (status != errSecSuccess) return set_keychain_error(status, "store");
if (status != errSecSuccess) return set_keychain_error(status, "store an item in");
Py_RETURN_NONE;
}
@ -1604,7 +1607,7 @@ cocoa_keychain_read_secret(PyObject *self UNUSED, PyObject *args) {
restore_keychain_interaction(ki);
CFRelease(q);
if (status == errSecItemNotFound) Py_RETURN_NONE;
if (status != errSecSuccess) return set_keychain_error(status, "read");
if (status != errSecSuccess) return set_keychain_error(status, "read an item from");
if (!result || CFGetTypeID(result) != CFDataGetTypeID()) {
if (result) CFRelease(result);
PyErr_SetString(PyExc_OSError, "The item read from the keychain has no data");
@ -1627,12 +1630,50 @@ cocoa_keychain_delete(PyObject *self UNUSED, PyObject *args) {
restore_keychain_interaction(ki);
CFRelease(q);
if (status == errSecItemNotFound) Py_RETURN_FALSE;
if (status != errSecSuccess) return set_keychain_error(status, "delete");
if (status != errSecSuccess) return set_keychain_error(status, "delete an item from");
Py_RETURN_TRUE;
}
static PyObject *
cocoa_keychain_list_accounts(PyObject *self UNUSED, PyObject *args) {
const char *service;
if (!PyArg_ParseTuple(args, "s", &service)) return NULL;
CFMutableDictionaryRef q = keychain_query(service, NULL);
if (!q) return NULL;
// Only the attributes are read, which does not need access to the secret data of the items
CFDictionarySetValue(q, kSecReturnAttributes, kCFBooleanTrue);
CFDictionarySetValue(q, kSecMatchLimit, kSecMatchLimitAll);
set_keychain_query_ui_fail(q);
CFTypeRef result = NULL;
KeychainInteraction ki = disallow_keychain_interaction();
OSStatus status = SecItemCopyMatching(q, &result);
restore_keychain_interaction(ki);
CFRelease(q);
if (status == errSecItemNotFound) return PyList_New(0);
if (status != errSecSuccess) return set_keychain_error(status, "list the items in");
if (!result || CFGetTypeID(result) != CFArrayGetTypeID()) {
if (result) CFRelease(result);
PyErr_SetString(PyExc_OSError, "Listing the items in the keychain did not return a list");
return NULL;
}
PyObject *ans = PyList_New(0);
CFArrayRef items = (CFArrayRef)result;
for (CFIndex i = 0; ans && i < CFArrayGetCount(items); i++) {
CFTypeRef item = CFArrayGetValueAtIndex(items, i);
if (!item || CFGetTypeID(item) != CFDictionaryGetTypeID()) continue;
CFTypeRef account = CFDictionaryGetValue((CFDictionaryRef)item, kSecAttrAccount);
if (!account || CFGetTypeID(account) != CFStringGetTypeID()) continue;
char buf[1024];
if (!CFStringGetCString((CFStringRef)account, buf, sizeof(buf), kCFStringEncodingUTF8)) continue;
RAII_PyObject(a, PyUnicode_FromString(buf));
if (!a || PyList_Append(ans, a) != 0) Py_CLEAR(ans);
}
CFRelease(result);
return ans;
}
// }}}
static PyMethodDef module_methods[] = {
{"cocoa_keychain_list_accounts", (PyCFunction)cocoa_keychain_list_accounts, METH_VARARGS, ""},
{"cocoa_keychain_store_secret", (PyCFunction)cocoa_keychain_store_secret, METH_VARARGS, ""},
{"cocoa_keychain_read_secret", (PyCFunction)cocoa_keychain_read_secret, METH_VARARGS, ""},
{"cocoa_keychain_delete", (PyCFunction)cocoa_keychain_delete, METH_VARARGS, ""},

View file

@ -900,6 +900,9 @@ def cocoa_keychain_read_secret(service: str, account: str) -> Optional[Secret]:
def cocoa_keychain_delete(service: str, account: str) -> bool:
pass
def cocoa_keychain_list_accounts(service: str) -> List[str]:
pass
def cocoa_set_menubar_title(title: str) -> None:
pass

View file

@ -39,6 +39,7 @@ PROCESS_FILE = 'process.json'
SCROLLBACK_DIR = 'scrollback'
ATTEMPTS_FILE = 'attempts'
KEY_ID_FILE = 'key-id'
KEY_ID_BYTES = 16
KEYCHAIN_SERVICE = 'net.kovidgoyal.kitty.session-saved-at-logout'
ENCRYPTED_FILE_MAGIC = b'kitty-snapshot-1'
IV_SIZE, TAG_SIZE = 12, 16
@ -70,6 +71,7 @@ class KeyStore(Protocol):
def store(self, key_id: str, key: Secret) -> None: ...
def read(self, key_id: str) -> Secret | None: ...
def delete(self, key_id: str) -> None: ...
def list_ids(self) -> list[str]: ...
class MacOSKeychain:
@ -88,6 +90,11 @@ class MacOSKeychain:
cocoa_keychain_delete(KEYCHAIN_SERVICE, key_id)
def list_ids(self) -> list[str]:
from .fast_data_types import cocoa_keychain_list_accounts
return cocoa_keychain_list_accounts(KEYCHAIN_SERVICE)
def get_key_store() -> KeyStore | None:
return MacOSKeychain() if is_macos else None
@ -152,6 +159,37 @@ def delete_key(key_store: KeyStore, key_id: str, path: str) -> None:
log_error(f'Failed to delete the encryption key for the session saved at logout in {path} from the keychain. Error: {e}')
def new_key_id() -> str:
return secrets.token_hex(KEY_ID_BYTES)
@run_once
def key_id_pat() -> 're.Pattern[str]':
return re.compile(f'[0-9a-f]{{{2 * KEY_ID_BYTES}}}')
def remove_orphaned_keys(base: str, key_store: KeyStore | None) -> None:
# Must be called with the lock held. Deletes the keys of snapshots that no longer exist, for example because they were deleted
# by something other than kitty. Snapshots being saved or restored hold the lock, so their keys are never orphans here.
if key_store is None:
return
try:
key_ids = key_store.list_ids()
except OSError as e:
log_error(f'Failed to list the encryption keys for sessions saved at logout in the keychain. Error: {e}')
return
used = set()
with suppress(FileNotFoundError), os.scandir(base) as entries:
for entry in entries:
if key_id := read_key_id(entry.path):
used.add(key_id)
pat = key_id_pat()
for key_id in key_ids:
# Only keys created by kitty, so items added by anything else with the same service are not touched
if key_id not in used and pat.fullmatch(key_id) is not None:
delete_key(key_store, key_id, base)
def remove_snapshot(path: str, key_store: KeyStore | None) -> None:
# The key is deleted first, so that the snapshot cannot be read even if deleting its files fails or leaves copies on disk
if (key_id := read_key_id(path)) and key_store is not None:
@ -242,7 +280,7 @@ def save_snapshot(base: str, pid: int, session: str, scrollback: Mapping[int, by
# Must be called with the lock held. Nothing is saved if the key cannot be stored. The snapshot is written to a temporary
# directory and renamed, so that an incomplete snapshot is never restored.
key_store = require_key_store(key_store)
key, key_id = random_secret(), secrets.token_hex(16)
key, key_id = random_secret(), new_key_id()
key_store.store(key_id, key)
tdir = ''
try:
@ -276,6 +314,7 @@ def remove_stale_snapshots(base: str, started_at: float, key_store: KeyStore | N
remove_snapshot(entry.path, key_store)
except FileNotFoundError:
pass
remove_orphaned_keys(base, key_store)
def save_session_at_logout(boss: BossType) -> None:
@ -353,6 +392,7 @@ def claim_snapshots(base: str, pid: int, key_store: KeyStore | None, is_alive: C
except Exception as e:
log_error(f'Failed to read the session saved at logout in {path}, deleting it. Error: {e}')
remove_snapshot(path, key_store)
remove_orphaned_keys(base, key_store)
ans.sort(key=lambda s: s.saved_at)
return ans
@ -443,3 +483,4 @@ def remove_all_snapshots() -> None:
for entry in entries:
remove_snapshot(entry.path, key_store)
remove_path(base)
remove_orphaned_keys(base, key_store)

View file

@ -155,8 +155,10 @@ class TestSessions(BaseTest):
finish_restore,
is_logout_in_progress,
load_snapshot,
new_key_id,
read_key_id,
remove_all_snapshots,
remove_orphaned_keys,
remove_stale_snapshots,
restore_snapshots,
save_snapshot,
@ -181,6 +183,11 @@ class TestSessions(BaseTest):
def delete(self, key_id: str) -> None:
self.keys.pop(key_id, None)
def list_ids(self) -> list[str]:
if self.fail:
raise OSError('User interaction is not allowed')
return list(self.keys)
errors: list[str] = []
log_error.redirect = errors.append
self.addCleanup(delattr, log_error, 'redirect')
@ -252,18 +259,42 @@ class TestSessions(BaseTest):
def swap(path: str) -> None:
os.replace(os.path.join(path, 'session.kitty-session'), os.path.join(path, 'process.json'))
for name, damage in (
('missing key', lambda path: ks.keys.clear()),
('keychain needs interaction', lambda path: setattr(ks, 'fail', True)),
('modified', modify),
('swapped', swap),
for name, damage, num_errors in (
('missing key', lambda path: ks.keys.clear(), 1),
# both reading the key and listing keys to remove orphans fail
('keychain needs interaction', lambda path: setattr(ks, 'fail', True), 2),
('modified', modify, 1),
('swapped', swap, 1),
):
with self.subTest(name):
errors.clear()
damage(save(13))
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
ks.fail = False
self.ae((os.listdir(base), len(errors)), ([], 1))
self.ae((os.listdir(base), len(errors)), ([], num_errors))
# Keys of snapshots deleted by something other than kitty are deleted, but not the keys of existing snapshots or keys
# not created by kitty
path = save(15)
orphan, foreign = new_key_id(), 'some-other-item'
ks.keys[orphan] = ks.keys[foreign] = ks.keys[read_key_id(path)]
remove_orphaned_keys(base, ks)
self.ae(sorted(ks.keys), sorted((read_key_id(path), foreign)))
# Orphans are removed when saving and claiming, and all keys when all snapshots are removed
ks.keys[orphan] = ks.keys[foreign]
remove_stale_snapshots(base, 0, ks)
self.assertNotIn(orphan, ks.keys)
ks.keys[orphan] = ks.keys[foreign]
self.ae(len(claim_snapshots(base, 1, ks, alive.__contains__)), 1)
self.assertNotIn(orphan, ks.keys)
# Failing to list the keys is logged, not raised
errors.clear()
ks.fail = True
remove_orphaned_keys(base, ks)
ks.fail = False
self.ae(len(errors), 1)
shutil.rmtree(base)
ks.keys.clear()
# Files are bound to their names, so swapping the scrollback of two windows is detected
path = save(14)