Ubuntu

gpg: agent_genkey failed: Permission denied

GPGキーの取り扱いについて学習していて、タイトルのエラーが発生した。

Ubuntu 22.04サーバーにSSHで接続し、suコマンドでユーザーを切り替えて、そこでキーペアを作成しようとしたら発生。
元のユーザーに戻って作る分には問題ない。



広告


具体的には、以下のような操作と結果であった。

$ su - hogedomain\\piyo
または
$ sudo su - hogedomain\\piyo
$ export GPG_TTY=$(tty)
$ gpg --full-generate-key
gpg (GnuPG) 2.2.27; Copyright (C) 2021 Free Software Foundation, Inc.
…
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: agent_genkey failed: Permission denied
Key generation failed: Permission denied

結論、suでユーザーを切り替える際に -P をパラメーターに加えると、キーペアを作ることができるようになった。
-Pはセッションの疑似端末を作成するオプション。

$ su -P - hogedomain\\piyo
または
$ sudo su -P - hogedomain\\piyo

調べたこと

エラーに遭遇したので探してみたら、このような情報にぶつかった。
Red Hat Bugzilla – Bug 659512 – no chance to enter a password during key generation in command-line mode

$ script /dev/null
$ export GPG_TTY=$(tty)

これでパスフレーズ入力画面が表示され、GPGキーを生成することができた。

なぜ、これだと実行できるのかを探してみると、scrpitが疑似端末を作成するから、と書かれている。
serverfault / Why does redirecting ‘script’ to /dev/null/ allow ‘screen’ to work while su’ed as another user?

では…と、確認してみた。
冒頭のやり方だと、suまえのttyを使うことになっていて、書き込み権限がない。

$ su - hogedomain\\piyo
$ ll /dev/pts
total 0
drwxr-xr-x  2 root   root      0 Sep 29 11:00 ./
drwxr-xr-x 19 root   root   4040 Sep 29 11:01 ../
crw--w----  1 rohhie tty  136, 0 Sep 29 11:32 0
c---------  1 root   root   5, 2 Sep 29 11:00 ptmx

$ tty
/dev/pts/0

こちらは、TTYはできるけれども、書き込み権限がない。

$ sudo su - hogedomain\\piyo
$ ll /dev/pts
total 0
drwxr-xr-x  2 root   root      0 Sep 29 11:00 ./
drwxr-xr-x 19 root   root   4040 Sep 29 11:01 ../
crw--w----  1 rohhie tty  136, 0 Sep 29 11:32 0
crw--w----  1 root   tty  136, 1 Sep 29 11:33 1
c---------  1 root   root   5, 2 Sep 29 11:00 ptmx

$ tty
/dev/pts/1

きっとTTYを作るオプションがあるはず…と探してみると -P だった。

$ su -P - hogedomain\\piyo
$ ll /dev/pts
total 0
drwxr-xr-x  2 root            root      0 Sep 29 11:00 ./
drwxr-xr-x 19 root            root   4040 Sep 29 11:01 ../
crw--w----  1 rohhie          tty  136, 0 Sep 29 12:01 0
crw-------  1 HOGEDOMAIN\piyo tty  136, 1 Sep 29 12:01 1
c---------  1 root            root   5, 2 Sep 29 11:00 ptmx

$ tty
/dev/pts/1

sudoで実行するとTTYが2つできるけれど、書き込み可能なTTYが使えるようになっていた。

$ sudo su -P - hogedomain\\piyo
$ ll /dev/pts
total 0
drwxr-xr-x  2 root            root      0 Sep 29 11:00 ./
drwxr-xr-x 19 root            root   4040 Sep 29 11:01 ../
crw--w----  1 rohhie          tty  136, 0 Sep 29 12:03 0
crw--w----  1 root            tty  136, 1 Sep 29 12:03 1
crw-------  1 HOGEDOMAIN\piyo tty  136, 2 Sep 29 12:03 2
c---------  1 root            root   5, 2 Sep 29 11:00 ptmx

$ tty
/dev/pts/2

このことは、他でも使うことがあるかもしれないな、と思ったのでメモしておくことにした。

広告

コメントはこちらから お気軽にどうぞ ~ 投稿に関するご意見・感想・他