SSH

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page SSH and the translation is 31% complete.
Outdated translations are marked like this.
Resources

SSH(Secure SHell)은 유닉스 같은 운영체제의 전통 텔넷 도구를 대체하는 암호화 터미널 프로그램입니다.

SSH (Secure SHell) is the ubiquitous tool for logging into and working on remote machines securely. All sensitive information is strongly encrypted, and in addition to the remote shell, SSH supports file transfer, and port forwarding for arbitrary protocols, allowing secure access to remote services. It replaces the classic telnet, rlogin, and similar non-secure tools - but SSH is not just a remote shell, it is a complete environment for working with remote systems.

게다가 원격 터미널 접근은 주요 ssh 바이너리로 제공하며, SSH 프로그램 모음은 scp(secure copy)와 sftp(secure file transfer protocol) 같은 다른 도구를 포함하며 발전했습니다.

원래 SSH는 free가 아니었습니다(여기서 free는 무료인지 자유인지 정확하지 않아 free로 표기했습니다. 역자 주). 그러나 오늘날 젠투에 미리 설치되어 나오는 OpenBSD의 OpenSSH는 가장 인기있는 프로그램이면서 SSH 구현체의 사실상 표준으로 자리잡았습니다.

SSH is multi-platform, and is very widely used: OpenSSH is installed by default on most Unix-like OSs, on Windows10, on MacOS, and can be installed on Android or "jailbroken" iOS (SSH clients are available). This makes SSH a great tool for working with heterogeneous systems.

설치

설치 검사

젠투 리눅스에서 대부분 배포하는 배포본에는 이미 시스템에 OpenSSH를 설치했습니다. ssh명령을 실행하면 확인할 수 있습니다. 만일 설치했다면 사용법 내용이 나타납니다:

user $ssh
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-E log_file] [-e escape_char]
           [-F configfile] [-I pkcs11] [-i identity_file]
           [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-p port]
           [-Q cipher | cipher-auth | mac | kex | key]
           [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] [user@]hostname [command]

사용법 내용이 나타나지 않는다면 ssh가 깨졌거나 설치하지 않았을 경우입니다. 새 USE 설정으로 OpenSSH를 다시 빌드하면 간단하게 해결할 수 있습니다. 어떤 경우든 사용할 수 있는 USE 설정을 살펴보는 방향으로 진행하십시오.

If this does not try to install OpenSSH, the package may have been masked, or even listed in package.provided, though this would be unusual.

USE 플래그

USE flags for net-misc/openssh Port of OpenBSD's free SSH release

X Add support for X11
audit Enable support for Linux audit subsystem using sys-process/audit
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
kerberos Add kerberos support
ldns Use LDNS for DNSSEC/SSHFP validation.
libedit Use the libedit library (replacement for readline)
livecd Enable root password logins for live-cd environment.
pam Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip
pie Build programs as Position Independent Executables (a security hardening technique)
security-key Include builtin U2F/FIDO support
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
ssl Enable additional crypto algorithms via OpenSSL
static !!do not set this during bootstrap!! Causes binaries to be statically linked instead of dynamically
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
verify-sig Verify upstream signatures on distfiles
xmss Enable XMSS post-quantum authentication algorithm

Emerge

필요한 USE 플래그를 바꾼 후 OpenSSH 설치(또는 다시 빌드)를 잊지 마십시오:

root #emerge --ask --changed-use net-misc/openssh

After changing any global USE flags in make.conf that affect the OpenSSH package, emerge world to update to the new USE flags:

root #emerge --ask --verbose --update --deep --newuse @world

설정

키 생성

보안 쉘을 제공하려면, SSH에서 제공하는 암호화, 복호화, 해싱 함수 기능을 관리하는데 암호화 키를 사용합니다.

SSH 서비스를 처음 시작할때 시스템 키를 생성합니다. ssh-keygen 명령으로 키를 (다시) 생성할 수 있습니다.

root #ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N ""
root #ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ""
root #ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N ""

서버 설정

설정 파일의 위치 변경을 포함하는 OpenRC의 /etc/conf.d/sshd 에서 더 많은 설정을 할 수 있지만, SSH 서버는 보통 /etc/ssh/sshd_config 파일에서 설정합니다. 서버 설정하는 방법에 대한 자세한 내용은 sshd_config man page를 보십시오.

The server provides means to validate its configuration using test mode:

root #/usr/sbin/sshd -t
중요
Always validate the configuration changes prior restarting the service in order to keep the remote login available.

클라이언트 설정

ssh 클라이언트와 관련 프로그램 (scp, sftp 등)은 다음 파일에서 설정할 수 있습니다.

  • ~/.ssh/config
  • /etc/ssh/ssh_config

더 많은 정보는 ssh_config 설명서를 읽어보십시오:

침투 예방

ssh는 보통 공격을 받는 서비스입니다. 반복적으로 로그인에 실패하는 원격 사용자에 대한 로그를 감시하고 블랙 리스트에 올리는 sshguard & fail2ban 프로그램이 있습니다.

서비스

Commands to run the SSH server will depend on active init system.

OpenRC

OpenSSH를 기본 런레벨에 추가하십시오

root #rc-update add sshd default

다음 명령으로 sshd 데몬을 시작하십시오:

root #rc-service sshd start

OpenSSH 서버는 다른 OpenRC 관리 서비스처럼 다룰 수 있습니다:

root #rc-service sshd start
root #rc-service sshd stop
root #rc-service sshd restart
참고
rc-service sshd restart 명령을 실행할 때 서버에 남은 활성 SSH 연결은 영향을 받지 않습니다.

Systemd

시스템을 시작했을 때 OpenSSH 데몬을 시작하게 하려면:

root #systemctl enable sshd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib64/systemd/system/sshd.service.

OpenSSH 데몬을 지금 시작하려면:

root #systemctl start sshd.service

서비스를 시작했는지 확인하려면:

root #systemctl status sshd.service

사용법

Commands

OpenSSH provides several commands, see each command's man page for usage information:

Escape sequences

During an active SSH session, pressing the tilde (~) key starts an escape sequence. Enter the following for a list of options:

ssh>~?

Note that escapes are only recognized immediately after a newline. They may not always work with some shells, such as fish.

Passwordless authentication to a distant SSH server

git 서버 관리를 위한 간단한 방법입니다.

See also
For more details see the Security Handbook.
경고
Leaving the passphrase empty implies the private key file will not be encrypted. An attacker having access to the local filesystem will be able to read the private key.

클라이언트

클라이언트에서 다음 명령을 실행하십시오:

user $ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/larry/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/larry/.ssh/id_rsa.
Your public key has been saved in /home/larry/.ssh/id_rsa.pub.
The key fingerprint is:
de:ad:be:ef:15:g0:0d:13:37:15:ad:cc:dd:ee:ff:61 larry@client
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|     .           |
| . .. n   .      |
|   . (: . .      |
|  o   . . : .    |
| . ..: >.) .     |
|  * ?. .         |
| o.. .. ..       |
| :. .  ! .       |
+-----------------+

The default file names of the keys must not be changed, or the server may persist in asking for a password even after running ssh-copy-id as explained below. The file name will be one of:

  • id_rsa
  • id_ecdsa
  • id_ed25519

depending on the key algorithm used.

서버

사용자 계정이 서버에 있는지 확인하고 클라이언트의 id_rsa.pub 파일을 서버의 사용자 디렉터리에 위치한 ~/.ssh/authorized_keys 파일에 넣으십시오.

user $ssh-copy-id <server>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/larry/.ssh/id_ed25519.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
larry@<server>'s password: 
 
Number of key(s) added: 1
 
Now try logging into the machine, with:   "ssh '<server>'"
and check to make sure that only the key(s) you wanted were added.

Afterwards a passwordless login should be possible doing:

user $ssh <server>
larry@<server>

Then on the server, the file /etc/ssh/sshd_config should be set to PasswordAuthentication no.

단일 머신 시험

위 절차를 지역 머신에서 시험할 수 있습니다:

user $ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/larry/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
...
user $mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
user $ssh localhost

Remote services over ssh

SSH may be used to access remote services, such as HTTP, HTTPS, fileshares, etc., through an encrypted "tunnel". Remote service access is detailed in the SSH tunneling and SSH jump host articles.

Copying files to a remote host

The SFTP command, a part of SSH, uses the SSH File Transfer Protocol to copy files to a remote host. rsync is also an alternative for this.

참고
The OpenSSH 8.0 release notes, from 2019, state "The scp protocol is outdated, inflexible and not readily fixed. We recommend the use of more modern protocols like sftp and rsync for file transfer instead.". The OpenSSH 8.8 release notes, from 2021, state "A near-future release of OpenSSH will switch scp(1) from using the legacy scp/rcp protocol to using SFTP by default.".

ssh-agent

OpenSSH comes with ssh-agent, a daemon to cache and prevent from frequent ssh password entries. When run, the environment variable SSH_AUTH_SOCK is used to point to ssh-agent's communication socket. The normal way to setup ssh-agent is to run it as the top most process of the user's session. Otherwise the environment variables will not be visible inside the session.

Depending on the way the graphical user session is configured to launch, it can be tricky to find a suitable way to launch ssh-agent. As an example for the lightdm display manager, edit and change /etc/lightdm/Xsession from:

user $exec $command

into:

user $exec ssh-agent $command

To tell ssh-agent the password once per session, either run ssh-add manually or make use of the AddKeysToAgent option.

Recent Xfce will start ssh-agent (and gpg-agent) automatically. If both are installed both will be started which makes identity management especially with SmartCards more complicated. Either stop XFCE from autostarting at least SSH's agent or disable both and use the shell, X-session or similar.

user $xfconf-query -c xfce4-session -p /startup/ssh-agent/enabled -n -t bool -s false
user $xfconf-query -c xfce4-session -p /startup/gpg-agent/enabled -n -t bool -s false

Tips

Terminal multiplexers to preserve sessions

It is possible to use a terminal multiplexer to resume a session after a dropped connection. Tmux and Screen are two popular multiplexers that can be used to be able to reconnect to a session, even if a command was running when the connection dropped out.

SSH over intermittent connections

When on unstable Internet connections, or when roaming between networks (such as when moving wifi networks), mosh can help avoid dropping SSH sessions.

Open new tabs for session with Kitty terminal

By using the SSH kitten for the Kitty terminal emulator, it is possible to open new "tabs", or windows, on the current SSH session without having log in again.

Kitty also provides other practical SSH functionality.

Benchmark the optimal rounds for an ed25519 key

요령
It is highly advisable to conduct benchmarking for the ed25519 key generation process, particularly considering the default value of 16 rounds and the potential performance improvements achievable with higher round values.
파일 ssh-benchmark.shBenchmark SSH Ciphers
#!/bin/sh

rounds="16 32 64 100 150"
num_runs=20

for r in $rounds; do
    printf "Benchmarking 'ssh-keygen -t ed25519 -a %s' on average:\n" "$r"
    total_time=0
    i=1
    while [ $i -le $num_runs ]; do
        start_time=$(date +%s.%N)
        ssh-keygen -t ed25519 -a "$r" -f test -N test >/dev/null 2>&1
        end_time=$(date +%s.%N)
        runtime=$(echo "$end_time - $start_time" | bc)
        total_time=$(echo "$total_time + $runtime" | bc)
        rm test{,.pub} >/dev/null 2>&1
        printf "Run %s: %s seconds\n" "$i" "$runtime"
        i=$((i + 1))
    done
    average_time=$(echo "scale=3; $total_time / $num_runs"| bc)
    printf "Average execution time: %s seconds\n\n" "$average_time"
done
참고
It is highly recommended to perform benchmarking for ed25519 key generation, considering both security and performance aspects. While the highest recommended round may offer superior security, it's essential to find the optimal balance based on individual requirements and time constraints. By conducting benchmark tests, one can evaluate the trade-off between security and performance, ensuring the selection of an appropriate round value for ed25519 keys.

Benchmarking is a crucial process to measure the performance and efficiency of a system or a specific component, such as cryptographic algorithms. In the context of SSH (Secure Shell) ciphers, it is important to determine the optimal number of rounds for generating ed25519 keys.

The provided script, ssh-benchmark.sh, conducts benchmarking on the ssh-keygen command with different round values for ed25519 keys. The script executes the ssh-keygen command multiple times with varying round values and measures the execution time for each run. It then calculates the average execution time for each round value.

By benchmarking different round values, system administrators and security professionals can identify the optimal round value that strikes a balance between security and performance. Higher round values generally provide stronger security but can result in increased computational overhead. Finding the right balance ensures that ed25519 keys are generated efficiently without compromising security.

Benchmarking helps identify potential bottlenecks, vulnerabilities, or areas that require improvement in security systems. It assists in selecting the most suitable algorithms and configurations for a particular use case, ensuring that security measures are robust and effective.

문제 해결

문제를 해결하는데 도와줄 디버깅 모드 레벨은 3가지가 있습니다. -v 옵션은 SSH가 절차에 대한 디버깅 메시지를 출력하게 합니다. 연결, 인증, 설정 문제에 대한 디버깅에 쓸모가 있습니다. 여러개의 -v 옵션은 출력 내용을 더 자세하게 보여줍니다. 최대 상세 기록 수준은 3입니다.

user $ssh example.org -v
user $ssh example.org -vv
user $ssh example.org -vvv

Permissions are too open

An ssh connection will only work if the file permissions of the ~/.ssh directory and contents are correct.

  • The ~/.ssh directory permissions should be 700 (drwx------), i.e. the owner has full access and no one else has any access.
  • Under ~/.ssh:
    • public key files' permissions should be 644 (-rw-r--r--), i.e. anyone may read the file, only the owner can write.
    • all other files' permissions should be 600 (-rw-------), i.e. only the owner may read or write the file.

These permissions need to be correct on the client and server.

오래 연결된 상태에서 죽음

수많은 인터넷 접근 장치는 네트워크 주소 변환(NAT)을 수행하며, 네트워크상의 단일 IP를 가지고 있음에도 불구하고 집이나 사무실같은 개인 네트워크로부터 인터넷과 같은 외부 네트워크로 접근할 수 있도로 해주는 절차를 거칩니다. 불행하게도 모든 NAT 장치가 동일하게 만들어지는 것은 아니며, SSH가 사용하는 TCP 연결과 같은 경우 어떤 장치는 오래 살아있는것처럼 잘못 보이기도 합니다. 이는, ssh 클라이언트가 아직 빠져나가지 않았음에도 불구하고 원격 서버와의 상호작용이 갑자기 중단되는 것과 같은 현상이 보일 수도 있습니다.

이 문제를 해결하려면 OpenSSH 클라이언트와 서버 사이에서 'keep alive'를 보내거나, 살아있는 연결 상태를 관리하고 확인하는데 역점을 둔 보이지 않는 메시지를 보내도록 설정할 수 있습니다:

  • 로컬 서버에 연결한 모든 클라이언트를 살아있는 채로 유지하려면, /etc/ssh/sshd_config 파일에서 ClientAliveInterval 30 (또는 초 단위의 다른 값)을 설정하십시오.
  • 로컬 클라이언트에서 연결한 모든 서버를 살아있는 채로 유지하려면, /etc/ssh/ssh_config 파일에서 ServerAliveInterval 30 (또는 초 단위의 다른 값)을 설정하십시오.

For example, to modify the server's configuration, add following file:

파일 /etc/ssh/sshd_config/01_ClientAlive.confHelp disconnects occur less often (server)
# The following ClientAlive values will keep an inactive session open for 30 minutes
ClientAliveCountMax 60
ClientAliveInterval 30
#
# Deactivate TCPKeepAlive
TCPKeepAlive no

To modify the client's configuration, add following file:

파일 /etc/ssh/ssh_config/01_ServerAlive.confHelp disconnects occur less often (client)
# The following ServerAlive values will keep an inactive session open for 2 hours
ServerAliveInterval 60
ServerAliveCountMax 120

New key does not get used

This scenario covers the case when a key to access a remote system has been created, the public key installed on the remote system, but the remote system is (for some reason) not accessible via ssh. This can happen if the name of the keyfile is not known to ssh.

Confirm which key files ssh is trying by running it with one of the verbose options, as described at the start of the Troubleshooting section. The verbose output will include the names of the keyfiles it is trying, and the one (if any) that actually gets used.

The default key files for the system are listed in the /etc/ssh/ssh_config, see the commented-out lines containing IdentityFile directives.

There are several ways to use a key with a non-default name.

The key name can be specified on the command line every time:

user $ssh -i ~/.ssh/my_keyfile user@remotesys

Alternatively, add following ssh configuration file to add a special case for ssh to the remote system:

파일 /etc/ssh/ssh_config/02_remotesys.confDefine keyfiles to use for host remotesys
Host remotesys
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/my_keyfile

If any are specified, it appears to be necessary to specify all the desired keys on a remote host. Read up on the ssh IdentityFile.

X11 포워딩에서 포워딩 또는 터널링이 되지 않습니다

문제점: X11 포워딩을 수락하려 설정 파일에서 필요한 내용을 바꿨지만, 찾은 X 프로그램을 서버에서 실행하는데 클라이언트로 전달이 되지 않습니다.

해결책: 원격 서버 또는 호스트에 SSH 로그인을 하는 동안 어떤 일이 발생하는지, SSH 세션을 설정한 다음 DISPLAY 변수가 설정 해제되는지 설정 중인지 확인하십시오.

이 시나리오에 대한 시험은 원격으로 로그인 한 후, 다음 과정을 따릅니다:

user $echo $DISPLAY
localhost:10.0

서버 측의 X11UseLocalhost no 설정을 사용하여 localhost:10.0 또는 localhost2.local:10.0와 같은 값을 가져와야 합니다. 보통 :0.0같은 값을 가져온다면 ~/.bash_profile에서 DISPLAY 변수를 설정 해제하거나 초기화 하는지 확인하십시오. 만약 그렇다면 DISPLAY의 사용자 정의 초기화를 제거하거나 주석처리를 하든지 SSH에 로그인할 때 ~/.bash_profile의 실행을 막아버리십시오.

user $ssh -t larry@localhost2 bash --noprofile

명령의 larry 대신 적당한 사용자 이름으로 바꾸십시오.

~/.bashrc 사용자 파일에 alias로 지정하는 꼼수가 있습니다.

추가 참조

  • 젠투 리눅스 키체인 안내서
  • autossh - SSH 연결을 끊고 다시 자동으로 연결하는 행위를 감지합니다.
  • SCP - SSH 도구 모음에 딸려오는 보안 복사 프로그램
  • SFTP - SSH 도구 모음에 딸려오는 보안 파일 전송 프로토콜
  • SSHFS - FUSE 기반 SSH 보안 강화 마운트 클라이언트.

외부 자료