Thursday 8 February 2024

Why can't keyctl read my keys under tmux or screen sometimes, error: keyctl_read_alloc: Permission denied

 Another of my self-answered stackoverflow questions.

Apparently randomly sometimes, under screen or tmux, I can't read user keys from @u, I can read from other terminals, even keys that I just added:

When it works:

 $ keyctl pipe $(keyctl padd user test @u <<<"test messsage")
 test messsage

When it fails:

$ keyctl pipe $(keyctl padd user test @u <<<"test messsage")
keyctl_read_alloc: Permission denied

What causes this, how can I fix or prevent it?

This can occur when you close the shell session that created the tmux or screen session.

Closing the shell session will destroy the original session keyring so that it is no longer accessible when you re-attach under another session (or even as the screen or tmux windows keep running). Screen or tmux keeps the shells running but they don't keep the session keyring running.

The fix with a damaged tmux or screen window is to get a new keyctl session and link it to the user session.

$ keyctl new_session
$ keyctl link @u @s

(If you try keyctl link without first creating a new session you get the error: keyctl_link: Key has been revoked)

These two statements will fix any new processes spawned from that shell in that screen or tmux window, but won't affect new windows spawned from the existing tmux or screen process, or existing processes in the current window.

But what you want is for it never to be a problem in the first place.

You (or perhaps screen or tmux) should launch this new keyctl session when you start screen or tmux. Then when the launching shell logs out and destroys its session keyring it won't affect screen or tmux.

This expression prefix would do it for any command:

keyctl session - bash -c 'keyctl link @u @s && exec "$@"' key-session tmux

The text key-session is just a $0 label, it doesn't mean anything, it just gives a nice name in ps or top for th efew milliseconds that before the exec. You can pass additional arguments after tmux.

The steps create a new session, and then link the user keyring to the session keyring. I don't know why this needs doing, but it's a necessary step to make it work.

If you launch tmux (or screen) in this way, then all windows, subprocesses etc will have a persistent session that outlasts the launching session, so you can detach and logout without worry.

However, this creates a new session keyring, dropping the old one for all those subprocesses. If this matters then you will have to read up about names session keyrings and do some keyring linking.

No comments:

Post a Comment