====== Linux SSH ====== * [[http://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html|Top 20 OpenSSH Server Best Security Practices]] * [[http://lum7671.wordpress.com/2011/08/23/ssh-client-%EB%8A%90%EB%A6%B0-%EC%A0%91%EC%86%8D-%ED%95%B4%EA%B2%B0-solved-too-slow-connect-to-server/|SSH서버 접속이 느릴 경우 대처법]] * $HOME/.ssh_config 파일에 ''**AddressFamily inet**''를 추가한다. * [[http://server.dzone.com/articles/9-ssh-do%E2%80%99s-and-don%E2%80%99ts|9 SSH Do’s and Don’ts]] * [[http://www.cyberciti.biz/faq/linux-unix-test-internet-connection-download-upload-speed/|Linux / Unix: Test Internet Connection Speed From Console Over SSH Command Line]] * [[linux:ssh:tunnel|SSH Tunneling]] * [[linux:asbrucm|asbru-cm]] * [[linux:pac|PAC]] * [[:tabby|tabby]] * [[linux:ssh:keychain|ssh keychain]] * [[linux:electerm|electerm]] * [[linux:scp|scp]] ===== Private Key 생성 ===== ssh-keygen -t rsa -b 4096 -m pem -C "your_email@example.com" * Passphrase를 항상 넣는 것이 좋다. * ''id_rsa'' 파일은 개인키로 자신의 PC(Client)에 둔다. * ''*.pub'' 파일은 공개키로 접속 대상 서버 계정의 ''~/.ssh/authorized_keys'' 파일에 그 내용을 추가한다. * [[git:github|Github]] 참조. * ''ssh-keygen'' 최근 버전에서 ''-m pem'' 옵션이 없으면 private Key 헤더가 ''%%-----BEGIN OPENSSH PRIVATE KEY-----%%''로 시작한다면 호환 안되는 경우가 있을 수 있다. * [[:upsource|Upsource]] 등 일부 과거 시스템들의 호환성으 높이려면 ''-m pem'' 옵션 추가할 것. 헤더가 ''%%-----BEGIN RSA PRIVATE KEY-----%%''로 시작해야한다. * ''~/.ssh''에 있는 파일은 ''600'' 권한으로 설정해야한다. 해당 디렉토리도 권한 확인이 필요하다. chmod 700 ~/.ssh ==== 서버의 ''~/.ssh/authorized_keys'' 에 파일추가 ==== * [[https://linux.die.net/man/1/ssh-copy-id|ssh-copy-id(1) - Linux man page]] 명령으로 추가 가능. ssh-copy-id -f -i id_rsa.pub username@host ===== ssh-agent ===== * ''ssh-agent''에 Private Key를 등록해서 SSH 터널링시 자동 접속 할 수 있다. * ''ssh-agent''는 ''exec ssh-agent /bin/bash''로 실행해야 한다. exec ssh-agent /bin/bash ssh-add ~/.ssh/id_dsa * 키 등록이 안 될 경우 키 파일의 권한이 **0600**이 맞는지 확인 해 본다. chmod 600 ~/.ssh/id_rsa* * [[https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-a-password-prompt|ssh agent - How can I run ssh-add automatically, without a password prompt? - Unix & Linux Stack Exchange]] * [[https://wiki.gnome.org/Projects/GnomeKeyring/Ssh|Projects/GnomeKeyring/Ssh - GNOME Wiki!]] * [[linux:ssh:keychain|ssh keychain]] ===== ssh-agent forwarding ===== * local PC 에 원격 서버의 private key 를 두고, 이를 bastion 서버에 그대로 포워딩해주고, bastion 서버에서 해당 private key로 원격 서버에 접속 가능하게 한다. * 이렇게 하면 공용 bastion 서버에 private key를 두지 않기 때문에 좀 더 안전해진다. * [[https://aws.amazon.com/ko/blogs/security/securely-connect-to-linux-instances-running-in-a-private-amazon-vpc/|Securely Connect to Linux Instances Running in a Private Amazon VPC | AWS Security Blog]] * [[https://docs.github.com/en/developers/overview/using-ssh-agent-forwarding|Using SSH agent forwarding - GitHub Docs]] * [[https://sunshout.tistory.com/1893|Deep dive into Kernel :: SSH Agent forwarding]] * [[https://www.cloudsavvyit.com/25/what-is-ssh-agent-forwarding-and-how-do-you-use-it/|What is SSH Agent Forwarding and How Do You Use It? – CloudSavvy IT]] * [[https://dev.to/levivm/how-to-use-ssh-and-ssh-agent-forwarding-more-secure-ssh-2c32|SSH Agent Forwarding: How to use SSH properly and what is SSH Agent Forwarding - DEV Community]] * ''ssh -A'' 옵션으로 포워딩 ===== SSH 접속 인사 텍스트 ===== * ''/etc/motd'' 파일 편집하면 SSH 접속시 인사말을 지정할 수 있다. * 그런데 ''update-motd'' 애플리케이션이 작동하고 있을 때는 ''/etc/update-motd.d'' 의 스크립트가 순서대로 실행된 결과로 매번 ''/etc/motd'' 파일이 덮어써진다. * 따라서 ''update-motd'' 사용시에는 ''/etc/update-motd.d''에 원하는 스크립트를 넣어둬야 한다. ===== ~/.ssh/config ===== * ''~/.ssh/config''를 통해 SSH 접속을 단순화할 수 있다. * [[http://haruair.com/blog/2219|ssh config로 ssh 접속 간편하게 하기]] * [[http://nerderati.com/2011/03/simplify-your-life-with-an-ssh-config-file/|Simplify Your Life With an SSH Config File]] * 파일 권한 chmod 600 ~/.ssh/config * ''~/.ssh/config'' # 기본형태. ~/.ssh/id_rsa 를 사용할 경우 혹은 일반 비밀번호 인증의 경우 Host dev HostName IP 혹은 hostname User 계정명 IdentitiesOnly yes # 특정 key 지정 Host company HostName IP 혹은 hostname User 계정명 PreferredAuthentications publickey IdentityFile ~/.ssh/[private key] IdentitiesOnly yes # github.com git 계정 접속시에 대한 처리 Host github.com HostName github.com User git IdentityFile ~/.ssh/[github private key] IdentitiesOnly yes # 동일 2차 도메인 사용시 Host *.example.com User 계정명 PreferredAuthentications publickey IdentityFile ~/.ssh/[private key] IdentitiesOnly yes * [[https://gist.github.com/jexchan/2351996|동일 HostName, 동일 User 다중 Key]] ''Host github.com-SSHID'' 에서 ''Host'' 의 값을 ''github.com-myid'' 형태로 특정 값을 줘서 처리할 수 있고, 그 뒤 부터 ssh ''github.com-myid'' 같은 호출이 정상 작동한다. * [[https://stackoverflow.com/questions/7927750/specify-an-ssh-key-for-git-push-for-a-given-domain|Specify an SSH key for git push for a given domain - Stack Overflow]] * [[https://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807#450807|gitolite - How could I stop ssh offering a wrong key? - Server Fault]] ''IdentitiesOnly yes'' 설정도 주는게 좋다. 그렇지 않으면 우선 순위상에 있는 다른 키 파일들 뒤에 ''IdentityFile''에 설정한 파일이 뒤로 추가되는 형태로 시도된다.(''~/.ssh/id_dsa, ~/.ssh/id_rsa'' 등이 더 우선된다) * ''ProxyCommand'' * [[https://io.adafruit.com/blog/notebook/2016/09/27/ssh-config-includes/|SSH Config Includes]] * ''Include ~/.ssh/other_config'' ===== 접속 유지 Keep connection ===== * [[http://www.maketecheasier.com/keep-ssh-connections-alive-in-linux/|How to Keep SSH Connections Alive In Linux]] * 전역 설정은 ''/etc/ssh/ssh_config'' 파일에 다음을 추가 ServerAliveInterval 60 # 60은 60초를 의미함. 60초마다 null 패킷 전송 * 현재 접속 사용자에 대한 설정은 ''~/.ssh/config'' Host * ServerAliveInterval 60 # 혹은 특정 호스트 지정 Host *hostname.com ServerAliveInterval 60 * 권한 설정 chmod 600 ~/.ssh/config * ssh 데몬 재시작 sudo service ssh restart 혹은 명령행 옵션을 직접 줘도 됨 ssh -o ServerAliveInterval=60 hostname ===== Text 파일 Gzip 압축 전송 : 다른 서버의 파일을 현재 서버로 전송 ===== * [[http://www.commandlinefu.com/commands/view/4859/scp-with-compression.|scp with compression. | commandlinefu.com]] ssh 10.0.0.4 "cat /tmp/backup.sql | gzip -c1" | gunzip -c > backup.sql # or ssh 10.0.0.4 "gzip -c /tmp/backup.sql" |gunzip > backup.sql # 압축을 풀 생각이 없다면 ssh 10.0.0.4 "gzip -c /tmp/backup.sql" > backup.sql.gz ===== 디렉토리/파일 압축전송 : 현재 서버의 파일을 다른 서버로 전송 ===== * [[http://www.cyberciti.biz/faq/howto-use-tar-command-through-network-over-ssh-session/|Howto: Use tar Command Through Network Over SSH Session]] * [[http://possiblelossofprecision.net/?p=444|/dev/blog » scp from stdin]] * 디렉토리를 통째로 전송하기 # gzip 보다 압축률 좋은 xz 사용. tar cJ a/dir | ssh user@remotehost.com "cat >outfile.tar.xz" ===== sshpass ===== * ssh, scp 등의 비밀번호를 자동으로 입력해준다. # 비밀번호가 'SSHPASS' 환경변수로 전달됨. # bash로 부터 받을 때는 export SSHPASS 명시 sshpass -e ssh -o StrictHostKeyChecking=no 아이디@호스트주소 명령어 # 비밀번호 직접입력 sshpass -p비밀번호 ssh -o StrictHostKeyChecking=no 아이디@호스트주소 명령어 # 비밀번호 파일. 일반 텍스트로 비밀번호 넣어둠. 파일 권한을 others, group은 읽고 쓰기 못하게 할 것. sshpass -f /path/to/passfile ssh -o StrictHostKeyChecking=no 아이디@호스트주소 명령어 # expect와 함께 sshpass -f 사용시 ~ 을 통한 사용자 디렉토리 지정은 작동하지 않았음. * [[http://zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_sshpass_%EC%82%AC%EC%9A%A9%EB%B2%95|리눅스 sshpass 사용법]] ===== 명령 실행 execute command ===== 아래는 긴 명령을 ssh를 통해 실행하는 방법이다. 예제 자체는 ''jstat''으로 GC 상황 모니터링하는 것. ssh myhostname 'bash -s' <<'ENDSSH' # commands... ENDSSH ===== known_hosts 에 미리 호스트 추가 ===== * [[http://bcho.tistory.com/1227|SSH known_host 메모]] * [[https://linuxhint.com/category/ubuntu/|How to use ssh-keyscan on Ubuntu]] * [[https://man.openbsd.org/ssh-keyscan.1|ssh-keyscan(1) - OpenBSD manual pages]] ssh-keyscan -t rsa host명 >> ~/.ssh/known_host ssh-keyscan -t rsa -f host명들 이들어있는 파일명 >> ~/.ssh/known_host ===== no matching cipher found. ===== 아래와 같은 오류 발생시.. >> no matching cipher found. Their offer: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc,rijndael128-cbc,rijndael192-cbc,rijndael256-cbc,rijndael-cbc@lysator.liu.se 혹은 >> no matching key exchange method found. Their offer: diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 ''~/.ssh/config'' 마지막에 다음과 같은 설정 추가(알고리즘은 알아서..) Ciphers aes128-cbc,aes192-cbc,aes256-cbc # 필요한 경우 KexAlgorithms +diffie-hellman-group1-sha1 # Host 를 명시해서 설정하는게 나음 Host 123.123.123.123 KexAlgorithms +diffie-hellman-group1-sha1 혹은 명령행에 암호화 방식을 ''-c'' 옵션으로 직접 지정한다. ssh -c aes128-cbc kwon37xi@xxx.xx.xx.xx ===== no match host key type found ===== * 아래와 같은 형태의 메시지가 나온다면, Unable to negotiate with 192.168.1.1 port 22: no matching host key type found. Their offer: ssh-dss, ssh-rsa * 위에서와 같이 전역으로 혹은 특정 ''Host'' 에 다음과 같이 설정한다. HostkeyAlgorithms ssh-dss,ssh-rsa ===== SSH Pipe ===== * [[https://www.maketecheasier.com/ssh-pipes-linux/|How to Use SSH Pipes on Linux]] ===== SSH RSA private key 를 공유해도 괜찮은가? ===== * [[https://crypto.stackexchange.com/questions/2706/what-is-the-harm-if-i-publish-an-encrypted-rsa-private-key-publicly|public key - What is the harm if I publish an encrypted RSA private key publicly? - Cryptography Stack Exchange]] * **강력한 비밀번호로 passphrase를 걸었다면** 괜찮지만, bruteforce 공격에 대비해 주기적으로 바꿔주는게 좋다. ===== 참조 ===== * [[https://blog.programster.org/ssh-agent-cheatsheet|SSH Agent Cheatsheet | Programster's Blog]]