Назад | Перейти на главную страницу

Используйте ssh agent forward и libpam-ssh для подключения к определенному пользователю на сервере без пароля

Я пытаюсь добиться настройки.

Цель состоит в том, чтобы делать команды sudo без пароля.

Кстати, я использую Debian (Buster).

ssh       su
A ------> B:user X ------> B:userY
    ^                ^
using A's        using A's
 ssh key           ssh key

Это вообще возможно?

Feb 22 11:00:11 jeremydev sshd[4050]: Accepted publickey for juniko from 127.0.0.1 port 55484 ssh2: RSA SHA256:N1N2OMouB8WTpQtYEAt69Iar79D3vOdhIHo96kgbDbU
Feb 22 11:00:11 jeremydev sshd[4050]: pam_unix(sshd:session): session opened for user juniko by (uid=0)
Feb 22 11:00:11 jeremydev systemd-logind[513]: New session 100 of user juniko.
Feb 22 11:00:14 jeremydev sudo[4169]: pam_ssh_agent_auth: Beginning pam_ssh_agent_auth for user juniko
Feb 22 11:00:14 jeremydev sudo[4169]: pam_ssh_agent_auth: Attempting authentication: `juniko' as `juniko' using /etc/ssh/sudo_authorized_keys
Feb 22 11:00:14 jeremydev sudo[4169]: pam_ssh_agent_auth: Contacted ssh-agent of user juniko (1000)
Feb 22 11:00:14 jeremydev sudo[4169]: pam_ssh_agent_auth: Failed Authentication: `juniko' as `juniko' using /etc/ssh/sudo_authorized_keys

Вот пример журнала подключений:

OpenSSH_8.1p1 Ubuntu-5, OpenSSL 1.1.1d  10 Sep 2019
debug1: Reading configuration data /home/kwaadpepper/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "example.ovh" port 443
debug2: ssh_connect_direct
debug1: Connecting to example.ovh [XXX.XXX.XXX.XXX] port 443.
debug1: Connection established.
debug1: identity file .ssh/id_rsa type 0
debug1: identity file .ssh/id_rsa-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.1p1 Ubuntu-5
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.9p1
debug1: match: OpenSSH_7.9p1 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to example.ovh:443 as 'juniko'
debug3: put_host_port: [example.ovh]:443
debug3: hostkeys_foreach: reading file "/home/kwaadpepper/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/kwaadpepper/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from [example.ovh]:443
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: rsa-sha2-512,rsa-sha2-256,ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:qWW1mY2LmZVvhYmdR4Z0z6DBLZiS2JdmmxfYu4vUR/A
debug3: put_host_port: [XXX.XXX.XXX.XXX]:443
debug3: put_host_port: [example.ovh]:443
debug3: hostkeys_foreach: reading file "/home/kwaadpepper/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/kwaadpepper/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from [example.ovh]:443
debug3: hostkeys_foreach: reading file "/home/kwaadpepper/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/kwaadpepper/.ssh/known_hosts:2
debug3: load_hostkeys: loaded 1 keys from [XXX.XXX.XXX.XXX]:443
debug1: Host '[example.ovh]:443' is known and matches the ECDSA host key.
debug1: Found key in /home/kwaadpepper/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey in after 134217728 blocks
debug1: Will attempt key: .ssh/id_rsa RSA SHA256:N1N2OMouB8WTpQtYEAt69Iar79D3vOdhIHo96kgbDbU explicit agent
debug2: pubkey_prepare: done
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: .ssh/id_rsa RSA SHA256:N1N2OMouB8WTpQtYEAt69Iar79D3vOdhIHo96kgbDbU explicit agent
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 60
debug1: Server accepts key: .ssh/id_rsa RSA SHA256:N1N2OMouB8WTpQtYEAt69Iar79D3vOdhIHo96kgbDbU explicit agent
debug3: sign_and_send_pubkey: RSA SHA256:N1N2OMouB8WTpQtYEAt69Iar79D3vOdhIHo96kgbDbU
debug3: sign_and_send_pubkey: signing using rsa-sha2-512
debug3: send packet: type 50
debug3: receive packet: type 52
debug1: Authentication succeeded (publickey).
Authenticated to example.ovh ([XXX.XXX.XXX.XXX]:443).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug3: send packet: type 90
debug1: Requesting no-more-sessions@openssh.com
debug3: send packet: type 80
debug1: Entering interactive session.
debug1: pledge: network
debug3: receive packet: type 80
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug3: receive packet: type 4
debug1: Remote: /home/debian/.ssh/authorized_keys:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding
debug3: receive packet: type 4
debug1: Remote: /home/debian/.ssh/authorized_keys:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding
debug3: receive packet: type 91
debug2: channel_input_open_confirmation: channel 0: callback start
debug1: Requesting authentication agent forwarding.
debug2: channel 0: request auth-agent-req@openssh.com confirm 0
debug3: send packet: type 98
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug3: send packet: type 98
debug1: Sending environment.
debug3: Ignored env GJS_DEBUG_TOPICS
debug3: Ignored env SSH_AUTH_SOCK
debug3: Ignored env SESSION_MANAGER
debug3: Ignored env GNOME_TERMINAL_SCREEN
debug3: Ignored env SSH_AGENT_PID
debug3: Ignored env XDG_CURRENT_DESKTOP
debug1: Sending env LANG = fr_FR.UTF-8
debug2: channel 0: request env confirm 0
debug3: send packet: type 98
debug3: Ignored env XDG_SESSION_CLASS
debug3: Ignored env COLORTERM
debug3: Ignored env QT_IM_MODULE
debug3: Ignored env GPG_AGENT_INFO
debug3: Ignored env DESKTOP_SESSION
debug3: Ignored env USER
debug3: Ignored env XDG_MENU_PREFIX
debug3: Ignored env HOME
debug3: Ignored env GJS_DEBUG_OUTPUT
debug3: Ignored env QT4_IM_MODULE
debug3: Ignored env DBUS_SESSION_BUS_ADDRESS
debug3: Ignored env PWD
debug3: Ignored env GTK_MODULES
debug3: Ignored env XDG_CONFIG_DIRS
debug3: Ignored env WINDOWPATH
debug3: Ignored env _
debug3: Ignored env JOURNAL_STREAM
debug3: Ignored env GTK_IM_MODULE
debug3: Ignored env GNOME_DESKTOP_SESSION_ID
debug3: Ignored env MANAGERPID
debug3: Ignored env CLUTTER_IM_MODULE
debug3: Ignored env XDG_SESSION_DESKTOP
debug3: Ignored env LOGNAME
debug3: Ignored env GNOME_TERMINAL_SERVICE
debug3: Ignored env VTE_VERSION
debug3: Ignored env GNOME_SHELL_SESSION_MODE
debug3: Ignored env PATH
debug3: Ignored env XMODIFIERS
debug3: Ignored env SHELL
debug3: Ignored env XDG_RUNTIME_DIR
debug3: Ignored env XDG_SESSION_TYPE
debug3: Ignored env QT_ACCESSIBILITY
debug3: Ignored env XDG_DATA_DIRS
debug3: Ignored env USERNAME
debug3: Ignored env INVOCATION_ID
debug3: Ignored env SHLVL
debug3: Ignored env XAUTHORITY
debug3: Ignored env IM_CONFIG_CHECK_ENV
debug3: Ignored env DISPLAY
debug3: Ignored env TERM
debug3: Ignored env GDMSESSION
debug3: Ignored env IM_CONFIG_PHASE
debug3: Ignored env OLDPWD
debug3: Ignored env ZSH
debug3: Ignored env PAGER
debug3: Ignored env LESS
debug3: Ignored env LSCOLORS
debug3: Ignored env LS_COLORS
debug2: channel 0: request shell confirm 1
debug3: send packet: type 98
debug2: channel_input_open_confirmation: channel 0: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug3: receive packet: type 99
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0

Вы ищете ForwardAgent директива в /etc/ssh/ssh_config или ~/.ssh/config:

ForwardAgent

Определяет, будет ли соединение с агентом аутентификации (при его наличии) перенаправляться на удаленный компьютер. Аргумент должен быть да или нет (по умолчанию).

Пересылку агента следует включать с осторожностью. Пользователи с возможностью обхода файловых разрешений на удаленном хосте (для сокета Unix-домена агента) могут получить доступ к локальному агенту через перенаправленное соединение. Злоумышленник не может получить ключевой материал от агента, однако он может выполнять операции с ключами, которые позволяют им аутентифицироваться с использованием идентификаторов, загруженных в агент.

После того, как вы включите его на клиенте, вы можете проверить правильность работы пересылки через:

ssh-add -L

и убедитесь, что он содержит ключ, требуемый pam_ssh_agent_auth.

Редактировать: Хотя указанный выше вариант конфигурации (или -A параметр командной строки, о котором вы упоминаете в своем комментарии) почти наверняка открывает сокет Unix на сервере, который перенаправляет локальный агент ssh (чтобы убедиться, что запустите ssh с -v вариант и проверьте наличие строк вокруг debug1: Requesting authentication agent forwarding. для ошибок) ваш сценарий инициализации оболочки или другой системный компонент может заменить перенаправленный агент своим собственным (пустым) агентом.

Для дальнейшей отладки вопроса проверьте SSH_AUTH_SOCK переменная после входа на сервер:

printenv SSH_AUTH_SOCK

У перенаправленного сокета агента есть путь в форме /tmp/ssh-XXXXXXXX/agent.<pid>, где XXXXXXXX некоторые случайные символы и <pid> - это идентификатор процесса родителя оболочки (значение $PPID в баше). Даже если что-то перезапишет эту переменную, вы все равно можете найти путь с помощью:

ls /tmp/ssh-*/agent.$PPID

и восстановим его:

export SSH_AUTH_SOCK=/tmp/ssh-*/agent.$PPID

Остается вопрос, кто перезаписывает ваш SSH_AUTH_SOCK переменная. Если бы мне пришлось угадывать, я бы поискал в трепать файлы инициализации (в Debian 10 /etc/profile, /etc/profile.d/*.sh, ~/.bash_profile, ~/.bash_login, ~/.profile, /etc/bash.bashrc и ~/.bashrc) или будь systemd-logind начал ssh-agent.service:

systemctl --user status ssh-agent.service