#################

## sftp 명령어 ##

#################

=================================================================

OPENSSH-LAB> sftp 사용하기 

+--------+      +--------+

|        |        |          |

| Client | --->  | Server  |

|        |        |          |

+--------+      +--------+

  root     --->  user : topuser

                 port : 22

       

   Upload (put) ----->


   <----- Download (get)



usage: sftp [-1246Cpqrv] [-B buffer_size] [-b batchfile] [-c cipher]

          [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-l limit]

          [-o ssh_option] [-P port] [-R num_requests] [-S program]

          [-s subsystem | sftp_server] host

       sftp [user@]host[:file ...]

       sftp [user@]host[:dir[/]]

       sftp -b batchfile [user@]host



Client# sftp -P 22 sshuser@localhost      <-- -P <포트번호> 참고 : 포트번호가 22일때 생략 가능

sshuser@localhost's password:             <-- 비밀번호 입력

Connected to localhost.

sftp> help  <-- sftp 사용법 



sftp> ls    <-- 서버의 ls

sftp> lls   <-- 로컬의 ls

sftp> put /etc/passwd                     <-- 서버의 sshuser 계정에 로컬의 /etc/passwd 업로드 

sftp> pwd                                 <-- 서버의 경로출력

Remote working directory: /home2/sshuser

sftp> lpwd                                <-- 로컬의 경로출력

Local working directory: /root



sftp> lls passwd                          <-- 로컬의 passwd 가 없다는 것은 아직 다운로드를 하지 않았기 때문이다.

ls: passwd: No such file or directory

Shell exited with status 2


sftp> get passwd                          <-- 서버에서 passwd 다운로드

Fetching /home2/sshuser/passwd to passwd

/home2/sshuser/passwd                            100% 2891     2.8KB/s   00:00    


sftp> lls passwd                           <-- 다운로드한 후의 파일이 생성되었다.

passwd


====================================================================


OPENSSH-LAB> Windows 의 Xshell 에서 Server로 파일 업로드하기 

-- 조건 --

Server IP : 192.168.56.101 

Server Port : 22 


Xshell -> 로컬쉘 실행

Xshell:\> sftp 192.168.56.101 

sftp:/home2/sshuser> ls

sftp:/home2/sshuser> put c:\windows\system32\notepad.exe



id sshuser

pw 1234



====================================================================


====================================================================

OPENSSH-LAB> 알드라이브(구 알FTP) 를 이용해서 업로드하기 

다운로드 사이트 : http://www.altools.co.kr/Download/ALDrive.aspx -> 다운로드 -> 접속



====================================================================


====================================================================

OPENSSH-LAB> editplus 를 이용해서 업로드하기

다운로드 사이트 : http://editplus.co.kr -> 다운로드 -> 접속


!!! editplus는 주로 PHP 프로그래머들이 많이 사용한다.

!!! php 프로그래머와 협업을 할때 많이 사용하므로 세팅에 대한 내용은 아주 중요하다...

!!! php 프로그램도 이클립스 프로그램으로 사용할 수 있다.

!!!

!!! 이클립스는 java & jsp를 이용해서 프로그래밍할때 사용하므로 사용법을 알아두면 좋다.


- sftp 설정

파일 -> FTP -> FTP 설정 -> 추가 ->

설명 : myftp

FTP 서버 : 192.168.56.101

username : sshuser

password : 1234


고급옵션 -> 

암호화 : sftp 

포트 : 22




- 원격열기 

파일 -> FTP -> 원격열기 

sftp 

port 설정 



- 문서저장

파일 -> FTP -> 원격저장 -> 표시 -> public_html 로 들어간다.

파일명 : index.html 로 저장한다.

====================================================================


################

## scp 명령어 ##

################

**** scp 는 포트번호가 22번이 아니면 -P(대문자) 옵션을 사용한다. ****

**** 보안상 서버가 포트번호 22 를 다른 포트 (2200) 로 변경할때는 

**** alias 를 이용하면 편리하게 접속할 수 있다.

**** # alias scp='scp -P2200'


usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]

           [-l limit] [-o ssh_option] [-P port] [-S program]

           [[user@]host1:]file1 ... [[user@]host2:]file2



====================================================================

OPENSSH-LAB> scp 를 아래 조건에 맞게 sshuser 디렉토리에 복사 하시오.


조건1 : /etc/passwd 

Upload    : S <--- C 

Dowonload : S ---> C


- Upload (/etc/passwd 파일을 sshuser@localhost로 복사)

# scp  /etc/passwd sshuser@localhost:



- Dowonload (sshuser@localhost:passwd 파일을 /tmp 로 복사)

# scp  sshuser@localhost:passwd /tmp



- Upload (/etc 디렉토리를 sshuser@localhost 몽땅 복사)

- -r 옵션은 디렉토리를 복사할때 사용한다.

# scp -r /etc sshuser@localhost:

# scp -r -P 2200 /etc sshuser@localhost:etc2


- Dowonload (sshuser@localhost:etc 디렉토리를 몽땅 /tmp로 복사)

- -r 옵션은 디렉토리를 복사할때 사용한다.

# scp -r sshuser@localhost:etc /tmp

# scp -P2200 sshuser@localhost:group /tmp

====================================================================


====================================================================

OPENSSH-LAB> openssl 과 openssh를 삭제하기 위한 방법


1. openssh 삭제 

# /etc/init.d/sshd stop

# rm -f /etc/ssh

# rm -f /etc/init.d/sshd

# rm -f /etc/pam.d/sshd

# rm -rf /usr/local/openssh



2. openssl 삭제

# vi /etc/ld.so.conf

-- /etc/ld.so.conf --

  :

  :

/usr/local/openssl/lib/            <-- 라인 삭제 

-- /etc/ld.so.conf --


# ldconfig


# rm -rf /usr/local/openssl 



ld.so.conf 수정하고 ldconfig 해주자


yum -y erase openssh-server openssh openssh-clients


====================================================================


====================================================================

OPENSSH-LAB> openssl 과 openssh 의 설치를 쉘스크립트를 이용해서 자동화 시켜보자. 

자동화 설치 디렉토리 : /root/openssh

자동화 설치 파일 : openssh_install.sh


# install -m 700 /dev/null openssh_install.sh

# vi openssh_install.sh 


-- openssh_install.sh --

#!/bin/sh

sslversion=1.0.2o

sshversion=7.7p1

sslURL=http://www.openssl.org/source

sshURL=http://ftp.fr.openbsd.org/pub/OpenBSD/OpenSSH/portable


if [ ! -d $HOME/openssh ]; then

  mkdir $HOME/openssh 

fi


cd $HOME/openssh


if [ ! -f openssl-${sslversion}.tar.gz ]; then

  wget --no-check-certificate ${sslURL}/openssl-${sslversion}.tar.gz

fi

if [ ! -f openssh-${sshversion}.tar.gz ]; then

  wget ${sshURL}/openssh-${sshversion}.tar.gz

fi


#####################

## openssl install ##

#####################


if [ ! -x /usr/bin/gcc ]; then

  echo "gcc not found"

  exit 1

fi


tar xzf openssl-${sslversion}.tar.gz

cd openssl-${sslversion}

./config \

--prefix=/usr/local/openssl \

--openssldir=/usr/local/openssl \

threads zlib shared

make

make test

make install

echo "/usr/local/openssl/lib/" >> /etc/ld.so.conf 

ldconfig

cd ..


#####################

## openssh install ##

#####################


yum -y remove `rpm -qa|grep openssh` > /dev/null 2>&1

/etc/init.d/sshd stop   

rm -rf  /etc/ssh  


# 관련 라이브러리 설치

yum -y install pam-devel > /dev/null 2>&1 


# 압축해제

tar xzf openssh-${sshversion}.tar.gz

cd openssh-${sshversion}


# 버전수정

sed 's/_7.7//' version.h > version.h.bak

rm -f version.h 

mv version.h.bak version.h


# 환경설정

./configure \

--prefix=/usr/local/openssh \

--with-ssl-dir=/usr/local/openssl \

--with-privsep-user=sshd \

--with-zlib \

--with-tcp-wrappers \

--with-pam \

--with-md5-passwords


make

make install


# 세팅 

cd contrib/redhat

cp sshd.init /etc/init.d/sshd

cp sshd.pam /etc/pam.d/sshd

chkconfig --add sshd

ln -s /usr/local/openssh/bin/* /usr/bin

ln -s /usr/local/openssh/libexec/* /usr/sbin

ln -s /usr/local/openssh/sbin/* /usr/sbin

ln -s /usr/local/openssh/etc /etc/ssh


/etc/init.d/sshd start


-- openssh_install.sh --


# ./openssh_install.sh



그리고 ssh ssl 주소로 이동하여 최신버전 알아내고


최신 버전으로 다시 스크립트 수정하여 써야함 (버전 수정 쪽도 바꿔주셈)



--> 위 처럼 Bad yes/no argument: sandbox 에러나는 경우 /etc/ssh/sshd_config에서 110라인 UsePrivilegeSeparation sandbox에 주석을 추가한다


버전 확인



sed 's/_7.7//' version.h > version.h.bak 의미는


version.h 에서 _7.7을 지운 결과를 출력한다. 그걸 > 로 version.h.bak로 리다이렉트 시켰다.


====================================================================


====================================================================

LAB> 기존에 소스로 설치된 OpenSSH의 버전정보를 숨겨보자.

-->해보길...


# telnet localhost 2200 

따로 설정 안했으면 22 port로 접근하길

Trying 127.0.0.1...

Connected to localhost.localdomain (127.0.0.1).

Escape character is '^]'.

SSH-2.0-OpenSSH_6.4


# vi version.h   <-- OpenSSH 버전이 들어가있는 파일

-- version.h --

#define SSH_VERSION     "OpenSSH_HIDE"  <-- OpenSSH_6.4 -> OpenSSH_HIDE

  :

-- version.h --

# make clean

# ./configure \

--prefix=/usr/local/openssh \

--with-ssl-dir=/usr/local/openssl \

--with-privsep-user=sshd \

--with-zlib \

--with-tcp-wrappers \

--with-pam \

--with-md5-passwords 

# make 

# make install              <-- 실행파일 복사

# /etc/init.d/sshd restart  <-- 반드시 sshd 서버를 재시작한다.

# telnet localhost 2200

Trying 127.0.0.1...

Connected to localhost.localdomain (127.0.0.1).

Escape character is '^]'.

SSH-2.0-OpenSSH_HIDE     <-- 버전정보가 변경되었다.

====================================================================


====================================================================

OPENSSH-LAB> openssh를 yum 으로 설치하기


# yum -y install openssh-server openssh openssh-clients



# /etc/init.d/sshd start

# nc localhost 22

SSH-2.0-OpenSSH_4.3


====================================================================


#################################

## 공개키를 이용한 로그인 방법 ##

#################################


참고 : http://kltp.kldp.net/eunjea/ssh/index.html



ssh 로 로그인하기 위해서는 아래 2가지 인증방식을 제공한다.

1. id/pw 인증방식 

2. 공개키 인증방식 (보안상 id/pw 보다 더 안전하다)


===================================================================

OPENSSH-LAB> 공개키 인증방식 (암호가 없는) 으로 접속을 해보자.


-- 순서 --

1. 키(개인키/공개키)를 생성한다. ($HOME/.ssh)

2. 생성된 공개키를 서버에 저장한다. (authorized_keys)

3. 로그인  



sshuser에서

$ ssh sshuser@localhost  <-- .ssh 디렉토리를 생성


- 공개키 생성

client # ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa):  <-- 엔터

Enter passphrase (empty for no passphrase): <-- 암호문 입력에서 엔터

Enter same passphrase again: <-- 암호문 입력에서 엔터



# ls .ssh/

id_rsa  id_rsa.pub  known_hosts



- 공개키 복사 

# scp .ssh/id_rsa.pub sshuser@localhost:.ssh/authorized_keys


- 접속 (공개키가 있고 암호문이 없으므로 자동 로그인된다.)

# ssh sshuser@localhost

Last login: Wed Apr 16 20:55:34 2014 from localhost.localdomain

$


===================================================================


===================================================================

OPENSSH-LAB> 공개키 인증방식 (암호가 있는) 으로 접속을 해보자.


- 공개키 생성

client# ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa): 

/root/.ssh/id_rsa already exists.

Overwrite (y/n)? y

Enter passphrase (empty for no passphrase):  <-- 암호문 입력

Enter same passphrase again:                 <-- 암호문 입력



- 공개키 복사 

client# scp .ssh/id_rsa.pub sshuser@localhost:.ssh/authorized_keys

sshuser@localhost's password:    <-- pw 비번입력


- 접속 (공개키가 있고 암호문이 있을때 암호문을 입력해서 로그인) 

client# ssh sshuser@localhost

Enter passphrase for key '/root/.ssh/id_rsa':  <-- 암호문 입력

server$ 



- 접속 (공개키가 있을때 자동으로 로그인을 세팅)

client# ssh-agent 

SSH_AUTH_SOCK=/tmp/ssh-0F7lVMCjbv55/agent.3933; export SSH_AUTH_SOCK;

SSH_AGENT_PID=3934; export SSH_AGENT_PID;

echo Agent pid 3934;


- ssh-agent 환경변수 세팅

client# SSH_AUTH_SOCK=/tmp/ssh-0F7lVMCjbv55/agent.3933; 

client# SSH_AGENT_PID=3934 

client# export SSH_AUTH_SOCK SSH_AGENT_PID;


- ssh-add 로 비번 입력

client# ssh-add 

Enter passphrase for /root/.ssh/id_rsa: 

Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)


client# ssh sshuser@localhost

Last login: Wed Apr 16 23:00:40 2014 from localhost.localdomain

server$ exit



- Lock

# ssh-add -x

Enter lock password: <-- Lock 비번

Again:               <-- Lock 비번

Agent locked.


# ssh  sshuser@localhost <-- Lock 때문에 자동 로그인이 안된다.

Enter passphrase for key '/root/.ssh/id_rsa': 



- Unlock

# ssh-add -X

Enter lock password: 

Agent unlocked.

# ssh  sshuser@localhost

Last login: Thu Apr 24 14:31:45 2014 from localhost.localdomain



- 삭제 (ssh-add)

server# ssh-add -D

All identities removed.


- 삭제 (ssh-agent)

server# ssh-agent -k

server# unset SSH_AUTH_SOCK SSH_AGENT_PID




- 편하게 하기위해서는 파일로 저장하고 . 으로 실행한다.

server# ssh-agent -k > del_ssh-agent.txt

server# . del_ssh-agent.txt



win(xshell) -> server(client) ---> localhost(server)

===================================================================


===================================================================

OPENSSH-LAB> ssh-agent 생성/삭제

--> 해보길...

-- ssh-agent 생성 순서 --

1. ssh-agent 실행

2. 환경변수 세팅 


1. ssh-agent 실행

# ssh-agent 

SSH_AUTH_SOCK=/tmp/ssh-8TyDQZiCtdJQ/agent.4244; export SSH_AUTH_SOCK;

SSH_AGENT_PID=4245; export SSH_AGENT_PID;

echo Agent pid 4245;


2. 환경변수 세팅 

# SSH_AUTH_SOCK=/tmp/ssh-8TyDQZiCtdJQ/agent.4244 

# SSH_AGENT_PID=4245 

# export SSH_AGENT_PID export SSH_AUTH_SOCK;


-- ssh-agent 삭제 순서 --

1. ssh-agent -k 실행

2. 환경변수 삭제


1. ssh-agent -k 실행

# ssh-agent -k

unset SSH_AUTH_SOCK;

unset SSH_AGENT_PID;

echo Agent pid 4245 killed;


2. 환경변수 삭제

# unset SSH_AUTH_SOCK SSH_AGENT_PID

===================================================================


===================================================================

OPENSSH-LAB> ssh-add 생성/삭제  Lock/Unlock

--> 해보길...

-- 순서 --

1. ssh-agent 실행 

2. 환경변수 세팅 (파일로 저장하고 실행)

3. ssh-add 실행


# ssh-agent -t 3600 > ssh-agent.sh  (-t 3600은 ssh-agent 생존 시간임 3600초)

# . ssh-agent.sh


# ssh-add 

Enter passphrase for /root/.ssh/id_rsa: 

Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)


# ssh sshuser@localhost

$ exit


- ssh-add Lock 

# ssh-add -x

Enter lock password: 

Again: 

Agent locked.


# ssh sshuser@localhost

Enter passphrase for key '/root/.ssh/id_rsa':  <-- 비번 요청  



- ssh-agent Unlock

# ssh-add -X

Enter lock password: 

Agent unlocked.


# ssh-add  -l

2048 8b:32:fd:ac:2b:81:5d:92:7a:77:d3:89:2e:49:3c:ed /root/.ssh/id_rsa (RSA)

# ssh-add  -L

ssh-rsa AAAAB ...


# ssh-add -D

All identities removed.


# ssh sshuser@localhost

Enter passphrase for key '/root/.ssh/id_rsa':  <-- 비번 요청  

===================================================================


===================================================================

OPENSSH-LAB> ssh-agent 암호문을 변경


-- 옵션 --

-f <filename> : Filename of the key file.

-p            : Change passphrase of private key file.



# ssh-keygen -p or  # ssh-keygen -p -f ~/.ssh/id_rsa

Enter old passphrase: 

Key has comment '/root/.ssh/id_rsa'

Enter new passphrase (empty for no passphrase): 

Enter same passphrase again: 

Your identification has been saved with the new passphrase.

===================================================================


===================================================================

OPENSSH-LAB> SSH 서버의 문제가 있을때 확인해봐야 하는 것들


!!! 서버 : sshd를 설치하고 접속이 안되면 여러 상황이 있을 수 있지만 아래 

!!! 내용들을 확인하는 것이 중요하다.

!!! 

!!! 1. 방화벽에 의해서 IP or Port가 블럭되었는지 확인한다. ( iptables -nvL )

!!! 2. 데몬이 안뜰 수도 있다.  ( netstat -nltp | grep ssh )

!!! 3. 서버의 포트가 일치하지 않을 수 있으므로 포트를 확인한다.  ( netstat -nltp | grep ssh )

===================================================================


실습> 2개의 호스트간의 공개키를 이용해서 접근해보자.


CentOS1 : 192.168.56.101

CentOS2 : 192.168.56.102


CentOS1 # killall -9 ssh-agent

CentOS1 # rm -f .ssh/id_rsa*

CentOS1 # ssh-keygen 

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa):   <-- 엔터

Enter passphrase (empty for no passphrase):  <-- 20131225

Enter same passphrase again:  <-- 20131225

CentOS1 # ssh-agent

SSH_AUTH_SOCK=/tmp/ssh-kWPWdgaCtFC4/agent.31025; export SSH_AUTH_SOCK;

SSH_AGENT_PID=31026; export SSH_AGENT_PID;

echo Agent pid 31026;

CentOS1 # SSH_AUTH_SOCK=/tmp/ssh-kWPWdgaCtFC4/agent.31025

CentOS1 # export SSH_AUTH_SOCK;

CentOS1 # SSH_AGENT_PID=31026; 

CentOS1 # export SSH_AGENT_PID;

CentOS1 # ssh-add

Enter passphrase for /root/.ssh/id_rsa: <-- 20131225

Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)


CentOS2 # useradd sshuser

CentOS2 # echo 1234 | passwd --stdin sshuser

CentOS2 # install -o sshuser -g sshuser -d ~sshuser/.ssh


CentOS1 # scp -P22 ~/.ssh/id_rsa.pub \

> sshuser@192.168.56.102:.ssh/authorized_keys  <-- ID/PW O 복사가 가능


CentOS1 # ssh -p22 sshuser@192.168.56.102

                   <-- CentOS2

CentOS2 $ 



google에서 ssh-agent 검색


공개키가 없을때 

ssh 접속  <-- id/pw 접속 


공개키복사 

ssh 접속  <-- 공개키 접속(암호문을 직접입력)  or id/pw 접속 


ssh-agent, ssh-add 

ssh 접속  <-- 공개키 접속(암호문을 ssh-agent 가 대신 입력)


google에서 rsync over ssh 검색 


실습> rsync + ssh + 공개키 + crond 를 이용한 백업시스템 구축하기


!!! rsync 를 사용하는 방법

!!! 1. rsync 데몬을 실행하는 방법 (/etc/rsync.conf)

!!! 2. rsync over ssh 를 실행하는 방법


!!! 2 번인 SSH를 이용한 rsync는 ssh를 이용하므로 rsync 데몬을 사용할

!!! 필요가 없다.


!!! 조건 : root 로 접속이 가능(O)하고 root의 비번을 알고 있어야 된다.


백업서버     : 192.168.56.101   ssh port : 2200

백업대상서버 : 192.168.56.102   ssh port : 2200


-- 설정 --

192.168.56.101 # vi /etc/ssh/sshd_config

-- /etc/ssh/sshd_config --

Port 2200

PermitRootLogin yes

-- /etc/ssh/sshd_config --

192.168.56.101 # /etc/init.d/sshd restart


192.168.56.102 # vi /etc/ssh/sshd_config

-- /etc/ssh/sshd_config --

Port 2200

PermitRootLogin yes

-- /etc/ssh/sshd_config --

192.168.56.102 # /etc/init.d/sshd restart

192.168.56.102 # iptables -F               <-- 방화벽 잠시 중지


-- 연습 --

1. scp 로 /etc 백업  

2. rsync over ssh 로 /etc 백업  

3. rsync over ssh 로 공개키기반 /etc 백업

1. scp 로 /etc 백업  


192.168.56.101 # mkdir /backup; cd /backup

192.168.56.101 # scp -P 2200 -r 192.168.56.102:/etc .


192.168.56.101 # scp -P 2200 -r 192.168.56.102:/etc . 

         <-- scp로 (단점) 다시 복사


2. rsync over ssh 로 /etc 백업  

192.168.56.101 # rm -rf etc 

192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc . 

  :

  :

# rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc . 

root@192.168.56.102's password: 

receiving incremental file list

        <-- 여기에 아무것도 나오지 않으면

            안받아 왔다는 것이다.

sent 200 bytes  received 44955 bytes  18062.00 bytes/sec

total size is 56602039  speedup is 1253.51


192.168.56.102 # useradd abc      <-- 사용자 abc를 생성한다.


192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc . 

root@192.168.56.102's password: 

receiving incremental file list

etc/

etc/group

etc/group-

etc/gshadow

etc/gshadow-

etc/passwd

etc/passwd-

etc/shadow

etc/shadow-


sent 445 bytes  received 46685 bytes  18852.00 bytes/sec

total size is 56602251  speedup is 1200.98


3. rsync over ssh 로 공개키기반 /etc 백업


192.168.56.101 # killall -9 ssh-agent

192.168.56.101 # ssh-keygen

                 <-- passphrase : 20131225 입력


192.168.56.101 # scp -P2200 ~/.ssh/id_rsa.pub \

> 192.168.56.102:.ssh/authorized_keys 

root@192.168.56.102's password:            <-- 비밀번호 입력 

id_rsa.pub                        100%  408     0.4KB/s   00:00    


192.168.56.101 # ssh-agent > ssh-agent.txt

192.168.56.101 # . ssh-agent.txt


192.168.56.101 # ssh-add 

Enter passphrase for /root/.ssh/id_rsa:  <-- passphrase 입력 : 20131225

Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)


192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc . 

                  <-- 비번이 입력이 없으면 성공

192.168.56.102 # usreadd abc2 

192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc . 

                  <-- 비번이 입력이 없으면 성공

-- 연습 --

!!! 위에서의 단점 192.168.56.102 번이 root로 접근이 가능하다는 것이다.

!!! PermitRootLogin 은 3개의 값을 지정할 수 잇다.

!!! yes : root 접근허용 가능

!!! no  : root 접근허용 금지

!!! forced-commands-only : 

!!! 공개키의 명령만 실행하겠다는 의미로 

!!! root로 접근은 금지하되 특정 명령어는 가능하게 할때 사용한다.


1. 백업대상 서버에서 설정및 sshd 재시작

- /etc/ssh/sshd_config 에서 PermitRootLogin forced-commands-only

2. 백업서버에서 백업대상 서버로 root 로 접근이 가능한지 TEST

3. 백업대상 서버에서 공개키(authorized_keys) 파일을 수정

4. /root/bin/validate-rsync 생성

5. 백업서버에서 rsync 로 백업

6. 백업스크립트 작성 

7. crond 에 등록 


1. 백업대상 서버에서 설정

192.168.56.102 # vi /etc/ssh/sshd_config

-- /etc/ssh/sshd_config --

PermitRootLogin forced-commands-only   <-- 수정 (root : 로그인 X)

-- /etc/ssh/sshd_config --

192.168.56.102 # /etc/init.d/sshd restart


2. root 로 접근이 가능한지 TEST(아래 두 개 모두 root로 로그인이 안된다. ) 

192.168.56.101 # ssh -p 2200 192.168.56.102  

192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc .


3. 백업대상 서버에서 공개키(authorized_keys) 파일을 수정

192.168.56.102 # vi .ssh/authorized_keys

-- ~/.ssh/authorized_keys --

from="192.168.56.101",command="/root/bin/validate-rsync" ssh-rsa A....  

-- ~/.ssh/authorized_keys --

4. /root/bin/validate-rsync 생성

192.168.56.102 # install -m 700 /dev/null ~/bin/validate-rsync

192.168.56.102 # mkdir ~/bin

192.168.56.102 # vi ~/bin/validate-rsync

-- ~/bin/validate-rsync --

#!/bin/sh

case "$SSH_ORIGINAL_COMMAND" in

          *\&*) echo "Rejected" ;;

          *\(*) echo "Rejected" ;;

          *\{*) echo "Rejected" ;;

          *\;*) echo "Rejected" ;;

          *\<*) echo "Rejected" ;;

          *\`*) echo "Rejected" ;;

          rsync\ --server*) $SSH_ORIGINAL_COMMAND ;;

          *) echo "Rejected" ;;

esac

-- ~/bin/validate-rsync --


chmod 700 /root/.ssh/

chmod 600 /root/.ssh/authorized_keys

chmod 700 /root/bin

chmod 700 /root/bin/validate-rsync


5. 백업서버에서 rsync 로 백업

192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/etc .


6. 백업스크립트 작성 


192.168.56.101 # cd ~/bin

192.168.56.101 # install -m 700 /dev/null remote-backup.sh

192.168.56.101 # vi remote-backup.sh

-- remote-backup.sh --

#!/bin/sh


backupdir=/backup

today=$(date +%Y%m%d)


mkdir $backupdir/$today

cd $backupdir/$today


for dir in etc home bin

do

   rsync -avz -e "ssh -p 2200" 192.168.56.102:/$dir .

done

-- remote-backup.sh --

192.168.56.101 # ./remote-backup.sh



7. crond 에 등록 (새벽 4시 2분에 실행)


192.168.56.101 # cp remote-backup.sh /etc/cron.daily   




실습> rsync 실행해서 확인해보기

192.168.56.102 # while :

> do

>   ps auxww | grep rsync | grep -v grep

>   sleep 1

> done


192.168.56.101 # rsync -avz -e "ssh -p 2200" 192.168.56.102:/usr .

  :

  :


192.168.56.102 # ps aux | grep rsync 

root      2011  0.0  0.2   4596  1104 ?        Ss   18:28   0:00 /bin/sh /root/bin/validate-rsync

root      2028 28.8  0.3   9736  1848 ?        S    18:28   0:03 rsync

--server --sender -vlogDtprze.is . /usr  <-- rsync --server* 부분 참고


실습> authorized_keys 파일에 실행할 수 있는 파일을 bash로 지정해보자.

!!! forced-commands-only : 

!!! 공개키의 명령만 실행하겠다는 의미로 

!!! root로 접근은 금지하되 특정 명령어는 가능하게 할때 사용한다.


192.168.56.102 # vi /etc/ssh/sshd_config

-- /etc/ssh/sshd_config --

PermitRootLogin forced-commands-only       <-- 확인

-- /etc/ssh/sshd_config --

192.168.56.102 # cd ~/.ssh

192.168.56.102 # vi authorized_keys

-- authorized_keys --

from="192.168.56.101",command="/bin/bash"  <-- 수정

  :

  :

-- authorized_keys --

192.168.56.101 # ssh -p 2200 192.168.56.102 

Enter passphrase for key '/root/.ssh/id_rsa':  <-- passphrase 입력

192.168.56.102 # 


##################

## ssh 설정파일    ##

##################


/etc/ssh/sshd_config 파일은 sshd의 시스템 서버 설정파일

/etc/ssh/ssh_config 파일은 sshd의 시스템 클라이언트 설정파일


실습> 클라이언트 설정파일을 수정 후 포트가 2200 으로 열려있는 

서버에 접근해보자.

(ssh 서버가 22번 포트가 아닌 2200포트로 서비스 중인 서버에 접근할 때)


# ssh 192.168.56.102

ssh: connect to host 192.168.56.102 port 22: Connection refused


# vi ssh_config 

-- /etc/ssh/ssh_config --

  :

  :

Port 2200        <--  22를 2200으로 수정

  :

  :

-- /etc/ssh/ssh_config --


# ssh 192.168.56.102   <-- 2200 포트로 접근 (-p 2200 생략 가능) 

Enter passphrase for key '/root/.ssh/id_rsa': 



서버용 설정파일에 보면 

1. 주석문 (설명문) #

2. 지시자 (서버가 실행할때 동작을 변경하는 변수)


# ssh가 사용할 기본 포트 지정        

Port 22


# sshd 데몬이 귀를 기울일 주소이다. 0.0.0.0은 모든 IP를 얘기한다.

# ListenAddress 127.0.0.1 은 localhost 만 포트를 연다. 

ListenAddress 0.0.0.0  


# 프로토콜 버전 1, 2 가 있는데 오래전에 사용한 protocol version 1 은

# 보안상 현재는사용하지 않고 2만 사용한다.

Protocol 2

# HostKeys for protocol version 2

HostKey /usr/local/openssh/ssh_host_rsa_key

HostKey /usr/local/openssh/ssh_host_dsa_key



#Lifetime and size of ephemeral version 1 server key

#protocol version 1은 사용하지 않는다.

#서버의 키는 한번 접속이 이루어진 뒤에 자동적으로 다시 만들어진다. 

#다시 만드는 목적은 나중에 호스트의 세션에 있는 키를 캡처해서 암호를 

#해독하거나 훔친 키를 사용하지 못하도록 하기 위함 위함이다. 

#값이 0이면 키는 다시 만들어지지 않는다. 

#기본값은 3600초이다. 이값은 자동으로 키를 재생성하기 전까지 서버가 

# 대기할 시간을 초단위로 정의한다.

KeyRegenerationInterval 1h


# 서버 키에서 어느정도의 비트수를 사용할지 정의한다. 

# 최소값은 512이고 디폴트 값은 1024이다.

# protocol version 1은 사용하지 않는다.

ServerKeyBits 1024  


# /etc/syslog.conf에서 정의한 로그 facility 코드이다. 

# 가능한 값은 DAEMON, USER, AUTH, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, 

# LOCAL6, LOCAL7이다. 기본값은 AUTH이다. Facilith란 메시지를 생성하는 하위 시스템을 말한다.


SyslogFacility AUTH

# 로그 레벨을 지정하는 것이다. 가능한 값은 QUIET, FATAL, ERROR, INFO, VERBOSE 그리고 DEBUGS이다.

LogLevel INFO



#Authentication:

# 유저의 로그인이 성공적으로 이루어지 않았을 때 이 시간 후에 서버가 연결을 끊는 시간이다. 

#값이 0이면 제한    시간이 없다. 기본값은 120초이다. 

LoginGraceTime 2m


# 보안상 no로 해준다.

# root 로그인 허용여부를 결정하는 것이다. yes, no, forced-commands-only

PermitRootLogin no   


# RSA 인증의 시도여부를 정의한다. ssh1 프로토콜에만 사용하기 위해 예약된 것으로, 

# ssh1을 사용하고 운영상 보다 안전하게 운영하려면 이옵션을 yes로 설정해야 한다. 

# RSA는 인증을 하기위해 ssh-keygen 유틸리티에 의해 생성된 공개키와 비밀키 쌍을 사용한다. 

# 현재 문서에서는 보안상 ssh1 프로토콜을 사용하지 않으므로 주석처리한다.

RSAAuthentication yes

PubkeyAuthentication yes

#AuthorizedKeysFile .ssh/authorized_keys



# sshd가 rhosts 기반의 인증을 사용할 것인지 여부를 정의한다.  

# rhosts 인증은 안전하지 못하므로 ‘no’로 한다.

RhostsAuthentication no

## 내 sshd_config에는 이 옵션이 없다


#Don't read the user's ~/.rhosts and ~/.shosts files

#IgnoreRhosts 명령은 인증시 rhosts와 shosts 파일의 사용여부를 정의한다. 

보안상의 이유로 인증할 때 rhosts와 shosts 파일을 사용하지 않도록 한다.

IgnoreRhosts yes


RhostsRSAAuthentication no

- rhost나 /etc/hosts.equiv파일이 있으면 이것을 사용해 인증한다. 

이것은 보안상 별로 안좋은 방법이기 때문에 허용하지 않는다. 

RSA 호스트 인증과 맞추어 rhosts 인증의 사용여부를 정의한다.


#similar for protocol version 2

HostbasedAuthentication no

#Change to yes if you don't trust ~/.ssh/known_hosts for

#RhostsRSAAuthentication and HostbasedAuthentication

IgnoreUserKnownHosts yes

- ssh 데몬이 RhostsRSAAuthentication 과정에서 각 사용자의 $HOME/.ssh/known_hosts를 

무시할 것인지 여부를 정의한다. rhosts 파일을 허용하지 않았으므로 yes로 설정하는 것이 안전하다.



# 패스워드 인증을 허용한다. 

# 인증할 때 암호기반 인증방법의 사용 여부를 결정한다. 

# 강력한 보안을 위해 이옵션은 항상 ‘no‘로 설정해야한다.

PasswordAuthentication yes        


# 패스워드 인증을 할 때 비어있는 패스워드를 인정하는 것이다. 

PermitEmptyPasswords no



# 원격에서 X11 포워딩을 허용하는 것이다. 

# 이 옵션을 yes로 설정하면 xhost보다 안전한 방법으로 원격에 있는 

# X프로그램을 사용할 수 있다. 

# yes로 설정 후 데몬 재가동을 하고 테스트해 보자.

X11Forwarding no


#PrintMotd yes         

- 사용자가 로그인 하는 경우 /etc/motd (the message of the day) 파일의 내용을 보여줄 것인지 

여부결정. ssh 로그인을 환영하는 메시지나 혹은 공지사항 같은 것을 적어 놓으면 된다.


# PAM 인증모듈을 사용할 것이다.

UsePAM yes



# DNS 사용여부 

UseDNS no



# sftp는 프로토콜 버전 2에서 사용되는 것으로서 ssh와 같이 

# ftp의 보안을 강화하기 위해 사용되는 

# 보안 ftp프로그램이다. openssh를 설치하면 /usr/local/ssh/libexec/sftp-server파일이 설치된다. 

# 이것은 sftp 서버용 프로그램이다. 

# 클라이언트 sftp프로그램은 설치되지 않는다. 따라서 서버로 일단 가동시키고 원도용 ssh클라이언트 

# 프로그램이나 SSH2를 설치하면 sftp를 사용할 수 있다

Subsystem   sftp    /usr/libexec/openssh/sftp-server


# 로그인 허락할 계정을 적는다. 

Allowusers sshuser

Denyusers sshuser



X11Forwarding 테스트




실습> SSH 포트를 방화벽에서 접근시켜보자.


!!! iptables 는 커널의 넷필터를 제어해주는 도구이다.

!!! inbound/outbound 둘다 제어할 수 있지만 현재는 inbound 만 제어한다.


# /etc/init.d/iptables stop

# iptables -A INPUT -p tcp --dport 2200 -j ACCEPT 

# iptables -A INPUT -p tcp --dport 2300 -j ACCEPT 

# iptables -A INPUT -p tcp --dport 22 -j ACCEPT 

# iptables -A INPUT -j DROP

# iptables-save > /etc/sysconfig/iptables

# /etc/init.d/iptables start

# iptables -nvL


ssh-agent 하고 환경변수도 잘 해주고 ssg-add 도 다 했는데 공개키를 이용한 자동 로그인이 안된다면


ssh-agent 프로세스가 많이 떠있을 경우가 있음 kill 명령으로 다 죽여준다


그리고 환경변수도 set | grep SSH (대소문자 구분) 으로 확인하여


SSH_AGENT_PID와

SSH_AUTH_SOCK 값을 unset 해줌


그리고 다시 공개키 이용 자동 로그인 시도..



scp를 이용하여 root의 .ssh의 id_rsa.pub를 sshuser의 홈 디렉터리안에 있는 .ssh 디렉터리에 authorized_keys라는 이름으로 scp한다.

하지만 에러

scp: .ssh/authorized_keys: No such file or directory


아마도 sshuser의 홈 디렉터리안에.ssh 라는 디렉터리가 없는 듯 하다


sshuser로 로그인 하여 (su sshuser) ssh를 한 번 연결하고 끊으면


홈디렉터리 안에 .ssh 디렉터리가 생긴다.


다시 로그아웃(Logout, Ctrl + D)하고 scp를 다시 해보면 잘 될 거당