Как отлаживать неработающий сертификат RSA без пароля в OpenSSH на Alpine?

Я планирую написать и запустить несколько интеграционных тестов, используя настоящий SSH-клиент и SSH-сервер. Поскольку для этого требуется конфигурация на уровне сервера, я настраиваю тесты внутри Docker, чтобы можно было построить сервер с правильной спецификацией, запустить сервер OpenSSH и запустить тесты.

Часть моей системы требует, чтобы пользователь без полномочий root (называемый nonpriv) мог ssh подключаться к серверу без пароля. Я сгенерировал сертификаты сервера и пользовательские сертификаты без полномочий root. Я настроил localhost как известный хост (поэтому подлинность сервера уже подтверждена), но я изо всех сил пытаюсь настроить сертификат в качестве авторизованного ключа. Я хочу иметь возможность делать ssh localhost как пользователь nonpriv и автоматически получать оболочку. Однако он пропускает ключ и переходит к аутентификации по паролю, чего я не хочу.

Docker ENTRYPOINT таков, так что ключи сервера разные для каждого запуска:

#!/bin/sh
#
# With thanks to https://github.com/danielguerra69/alpine-sshd

if [ ! -f "/etc/ssh/ssh_host_rsa_key" ]; then
    # generate fresh rsa key
    ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
fi

if [ ! -f "/etc/ssh/ssh_host_dsa_key" ]; then
    # generate fresh dsa key
    ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa
fi

# Prepare run dir
if [ ! -d "/var/run/sshd" ]; then
  mkdir -p /var/run/sshd
fi

# Start the SSH daemon
/usr/sbin/sshd

# Generate an SSH key for the nonpriv user
su -c /tmp/install/generate-keys.sh nonpriv

# Sleep so we can debug the server while it is running
# Will be replaced by test runner when SSH client works!
sleep 10000

Как обычно для Docker, все это запускается как root, поэтому я использую su -c ближе к концу для генерации пользовательских ключей:

#!/bin/sh

mkdir -p /home/nonpriv/.ssh

# Add the server to recognised hosts
ssh-keyscan localhost >> /home/nonpriv/.ssh/known_hosts

# Generate an SSH key with an empty passphrase
ssh-keygen \
    -t rsa \
    -b 4096 \
    -f /home/nonpriv/.ssh/id_rsa \
    -N ''

# Add it to the list of authorised keys for self
ln -s /home/nonpriv/.ssh/id_rsa.pub /home/nonpriv/.ssh/authorized_keys

Как видите, я использую символическую ссылку, чтобы добавить открытый ключ в список авторизованных ключей. Затем я запускаю контейнер и оболочку Docker таким образом (где «silly_name» — это автоматически сгенерированное имя контейнера):

docker exec -it silly_name sh

Из оболочки я делаю это:

/ # whoami
root
/ # su nonpriv
/ $ whoami
nonpriv
/ $ ssh -vvv localhost
OpenSSH_7.4p1, LibreSSL 2.4.4
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolving "localhost" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.
debug1: identity file /home/nonpriv/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/nonpriv/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to localhost:22 as 'nonpriv'
debug3: hostkeys_foreach: reading file "/home/nonpriv/.ssh/known_hosts"
debug3: record_hostkey: found key type RSA in file /home/nonpriv/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa
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,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa,[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected],zlib
debug2: compression stoc: none,[email protected],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,[email protected],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: ssh-rsa,rsa-sha2-512,rsa-sha2-256
debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected]
debug2: compression stoc: none,[email protected]
debug2: languages ctos: 
debug2: languages stoc: 
debug2: first_kex_follows 0 
debug2: reserved 0 
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: rsa-sha2-512
debug1: kex: server->client cipher: [email protected] MAC: <implicit> compression: none
debug1: kex: client->server cipher: [email protected] 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: ssh-rsa SHA256:ierfDQtTWiobxAGsyEf1PrjRcmsr5jQbZVOzcNCnBo4
debug3: hostkeys_foreach: reading file "/home/nonpriv/.ssh/known_hosts"
debug3: record_hostkey: found key type RSA in file /home/nonpriv/.ssh/known_hosts:1
debug3: load_hostkeys: loaded 1 keys from localhost
debug1: Host 'localhost' is known and matches the RSA host key.
debug1: Found key in /home/nonpriv/.ssh/known_hosts:1
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey 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 after 134217728 blocks
debug2: key: /home/nonpriv/.ssh/id_rsa (0x5645c099ae80)
debug2: key: /home/nonpriv/.ssh/id_dsa (0)
debug2: key: /home/nonpriv/.ssh/id_ecdsa (0)
debug2: key: /home/nonpriv/.ssh/id_ed25519 (0)
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,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,password,keyboard-interactive
debug3: start over, passed a different list publickey,password,keyboard-interactive
debug3: preferred 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 RSA public key: /home/nonpriv/.ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Trying private key: /home/nonpriv/.ssh/id_dsa
debug3: no such identity: /home/nonpriv/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/nonpriv/.ssh/id_ecdsa
debug3: no such identity: /home/nonpriv/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/nonpriv/.ssh/id_ed25519
debug3: no such identity: /home/nonpriv/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup keyboard-interactive
debug3: remaining preferred: password
debug3: authmethod_is_enabled keyboard-interactive
debug1: Next authentication method: keyboard-interactive
debug2: userauth_kbdint
debug3: send packet: type 50
debug2: we sent a keyboard-interactive packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug3: userauth_kbdint: disable: no info_req_seen
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: 
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
nonpriv@localhost's password: 

Отсюда видно, что /home/nonpriv/.ssh/id_rsa имеется, но не удачно. Я перепробовал ряд ресурсов в Интернете, часто связанных с правами доступа к домашнему каталогу, папке ~/.ssh или файлу authorized_keys, но безрезультатно. Я буду продолжать попытки, но было бы полезно получить некоторую информацию от системы о том, в чем может быть проблема.

Я думаю, что можно настроить ключи для подключения по ssh к локальному хосту, поскольку я сделал это на своем ноутбуке для разработки (правда, с Mint 18 в качестве ОС, а не с Alpine/BusyBox).

К сожалению, в /var/log/ вообще нет журналов, поэтому здесь не так много информации. Куда я мог смотреть дальше?

Обновлять

На случай, если конфигурация sshd может быть важна, у меня есть конфигурация по умолчанию от Alpine:

$ less /etc/ssh/sshd_config

#   $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/bin:/usr/bin:/sbin:/usr/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile  .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem   sftp    /usr/lib/ssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#   X11Forwarding no
#   AllowTcpForwarding no
#   PermitTTY no
#   ForceCommand cvs server

person halfer    schedule 29.05.2017    source источник
comment
Вы включили аутентификацию RSAA в /etc/ssh/sshd_config? Обратите внимание на sshd в имени файла   -  person Robert    schedule 30.05.2017
comment
Спасибо за совет, @Robert, однако это не сильно изменилось. Раньше у меня его не было, но я его добавил. Теперь я получаю это: /etc/ssh/sshd_config line 121: Deprecated option RSAAuthentication. Кажется, это не имеет значения для входа без пароля.   -  person halfer    schedule 30.05.2017
comment
@ Роберт, это было решено! Смотри ниже.   -  person halfer    schedule 30.05.2017


Ответы (2)


Я решил эту проблему, хотя не совсем понимаю, почему это решает ее. (Я приму любые ответы вместо своих собственных, если у кого-то есть объяснение).

В моем Dockerfile я настраивал пользователя таким образом:

# -s specify a shell; -D = don't prompt for a password
RUN adduser -s /bin/sh -D nonpriv

Насколько я знаю, это просто пользователь с домашним каталогом и нулевым паролем. Однако похоже, что мне действительно нужно указать пароль, поэтому теперь я также делаю это:

# It looks like passwordless access does not work unless the user
# has a password!
RUN echo 'nonpriv:Password123' | chpasswd

Мне это кажется странным, так как системе доступа PPK не должно быть дела до того, какой у пользователя пароль и есть ли он.

Теперь я могу войти в себя по SSH:

/ $ whoami
nonpriv
/ $ ssh localhost
Welcome to Alpine!

The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org>.

You can setup the system with the command: setup-alpine

You may change this message by editing /etc/motd.

d4dded05c2d1:~$ 
person halfer    schedule 30.05.2017
comment
Мы внедряем многопользовательский SFTP-сервер и обеспечиваем использование ключей RSA. Мы столкнулись с одной и той же проблемой и нашли то же решение, но я был бы рад, если бы у кого-то была идея получше. Я бы предпочел не создавать пароли для каждого пользователя в нашей системе. - person Tony Bathgate; 06.10.2017
comment
@Tony: я не смог улучшить это, хотя, поскольку это только для тестов, мне это не нужно, и я не приложил к этому много усилий. Будет ли вам достаточно создать одинаковый (сложный) пароль для всех пользователей, а затем установить оболочку как /bin/false? Я думаю, что это устройство помешало бы им войти в систему, даже если бы они получили пароль. - person halfer; 06.10.2017
comment
Спасибо за идею. До сих пор мы устанавливали очень сложные пароли и настраивали openssh, чтобы он разрешал только SFTP. Думаю, мы тоже попробуем. Я все еще считаю, что это неудачный обходной путь и недостаток в альпийском. - person Tony Bathgate; 11.10.2017
comment
@Tony: может быть, стоит изучить ответ SSH receive packet: type 51? Мне кажется, что ключ RSA был неправильно отклонен. Интересно, стоит ли также создавать журнал успешного случая и различать два вывода. Если вы сможете свести это к очевидной ошибке, возможно, вы могли бы добавить проблему в список ошибок Alpine? - person halfer; 11.10.2017

В моем случае полностью беспарольный ssh ​​требовал также следующих настроек:

Host *
  StrictHostKeyChecking no
  UserKnownHostsFile=/dev/null

в файле /etc/ssh/ssh_config в докере

ENV APPUSER=myuser
    ENV UID=110
    ENV GID=110

    RUN set -x ; addgroup -g "$GID" -S "$APPUSER" && \
        adduser \
        -g "$GID" \
        -D \
        -s "/bin/bash" \
        -h "/home/$APPUSER" \
        -u "$UID" \
        -G "$APPUSER" "$APPUSER" && exit 0 ; exit 1

RUN echo "$APPUSER:secret-pass" | chpasswd
RUN ssh-keygen -A
RUN apk add --no-cache procps su-exec sudo coreutils supervisor && \
    apk add --no-cache openrc openssh && \
    mkdir -p /run/openrc/ && touch /run/openrc/softlevel && rc-update add sshd 
&& rc-status && \
rm  -rf /tmp/* /var/cache/apk/* && \
apk del .build-dependencies



USER myuser

RUN ssh-keygen -q -t rsa -N '' -C '' -f ~/.ssh/id_rsa && \
   cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys && \
   chmod 644 ~/.ssh/authorized_keys
person Yordan Georgiev    schedule 09.08.2019
comment
Я предполагаю, что вы не хотите, чтобы пароль работал - не работает ли secret-pass, и если да, то какая часть этого достигает этого? Я задавался вопросом, придется ли вам настраивать нулевую оболочку, но у вас здесь есть Bash. - person halfer; 09.08.2019
comment
Правильный. он НЕ работает с нулевой оболочкой с этими версиями sshd и alpine. Я даже не уверен, может ли он работать без фактического предоставления пароля пользователя ОС - я тестировал его с этой настройкой, но это не сработало ... Вопрос был о ssh без пароля, а не о пользователе ОС без пароля. .. - person Yordan Georgiev; 09.08.2019
comment
Пользователи SSH являются пользователями ОС, не так ли? - person halfer; 13.08.2019
comment
да - это частный id_rsa пользователя операционной системы myuser -f ~/.ssh/id_rsa . Моя настройка не работала с пользователями ОС, добавленными без пароля, то есть без этой строки RUN echo "$APPUSER:secret-pass" | chpasswd - вся настройка ssh не работала должным образом ... и не работала, установив нулевую оболочку по умолчанию для этого пользователя ОС !!! - person Yordan Georgiev; 13.08.2019