서버는 크게 두가지 유형으로 실행되며 openssh 는 두 가지 방식 모두 가능하다.


1. Standalone 방식

- openssh 

2. xinetd 방식 (inetd -> xinetd)

- openssh , telnet 


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

## OpenSSH 와 telnet 의 차이점        ##

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

o telnet 

인증방식 : IP/PW 인증

데이터 전송방식 : client와 server 간에 data를 평문(plaintext) 으로 전송한다.


평문 전송의 단점 :

네트워크상에서 암호화 통신이 안되므로 네트워크 공격기법인 스니핑에 쉽게 노출될 수 있다.  

보안상 취약하기 때문에 현재는 거의 사용되지 않는다.


o openssh 

인증방식 :  IP/PW 인증, 공개키 인증

데이터 전송방식 : client와 server 간에 data를 암호문(ciphertext) 으로 전송한다.


암호문 전송의 장점 : 

네트워크상에서 암호화 통신을 하므로 네트워크 공격기법인  스니핑 공격에 안전하다.

때문에 현재 거의 모든 서버가 ssh를 사용한다.


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

TELNET-LAB> telnet 서버를 설치해보자.


-- 설치순서 --

1. telnet-server 패키지를 설치

2. telnet server 데몬을 실행하기 위한 설정파일을 수정

3. xinetd 데몬 실행

4. telnet 서버로 접속 

5. 보안문제점 확인 


1. telnet-server 패키지를 설치

# rpm -qa | grep telnet

# yum search telnet

# yum -y install telnet-server




- 만약 yum 으로 설치가 안되면 아래 DVD를 이용해서 설치한다. 

- DVD를 넣고 마운트한 후에 xinetd, telnet-server 를 설치한다.

# mount -t iso9660 -o ro /dev/cdrom /media/

# rpm -Uvh /media/CentOS/xinetd-2.3.14-16.el5.i386.rpm 

# rpm -Uvh /media/CentOS/telnet-server-0.17-39.el5.i386.rpm 


2. telnet server 데몬을 실행하기 위한 설정파일 수정

# vi /etc/xinetd.d/telnet



-- telnet --

service telnet

{

  flags           = REUSE 

  socket_type     = stream        

  wait            = no    

  user            = root  

  server          = /usr/sbin/in.telnetd

  log_on_failure  += USERID

  disable         = no              <-- yes를 no 로 수정!!!

}

-- telnet --



3. xinetd 데몬 실행

# /etc/init.d/xinetd restart

# netstat -nltp   <-- 23번 포트 (telnet) 확인 

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      2025/sshd           

tcp        0      0 0.0.0.0:23                  0.0.0.0:*                   LISTEN      2161/xinetd         

tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1859/sendmail       



# iptables -I INPUT -p tcp --dport 23 -j ACCEPT \

> -m comment --comment "telnet-server"

# iptables -nL



# useradd linuxtest

# echo 12345 |  passwd --stdin linuxtest



4. telnet 서버로 접속

# telnet localhost

Trying 127.0.0.1...

Connected to localhost.localdomain (127.0.0.1).

Escape character is '^]'.

CentOS release 5.8 (Final)

Kernel 2.6.18-308.el5 on an i686

login: linuxtest

Password: 

[linuxtest@localhost ~]$ id

uid=501(linuxtest) gid=501(linuxtest) groups=501(linuxtest) context=user_u:system_r:unconfined_t:s0


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


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

OPENSSH-LAB> OpenSSH 서버를 최신 소스로 컴파일해보자.


공식사이트 : http://www.openssl.org

4509047 Apr  7 19:21:29 2014 openssl-1.0.1g.tar.gz [LATEST]


공식사이트 : http://www.openssh.com 

OpenSSH 6.6 released March 16, 2014


최신버전 : openssh-6.6p1.tar.gz


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

## openssl 설치 ##

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


openssh-6.6p1.tar.gz

openssl-1.0.1g.tar.gz


-- 설치 순서 --

0. 관련 패키지/라이브러리 설치

1. openssl 소스다운로드

2. 압축해제

3. 환경설정

4. 컴파일

5. 설치

6. 세팅 

7. 확인


0. 관련 패키지/라이브러리 설치 (설치가 안되어 있다면)

- 개발툴이 없다면 설치

- zlib-devel 패키지가 없다면 설치

# rpm -qa | grep zlib

zlib-1.2.3-7.el5       <-- 컴파일된 특정 패키지를 rpm 으로 설치할때 필요

zlib-devel-1.2.3-7.el5 <-- 소스파일을 컴파일할때 필요

# gcc

# make


# yum -y groupinstall "development tools"  

# yum -y install zlib-devel  



1. openssl 소스다운로드

# wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz


2. 압축해제

# tar xzf openssl-1.0.1g.tar.gz

# cd openssl-1.0.1g


3. 환경설정 

# ./config \

--prefix=/usr/local/openssl \

--openssldir=/usr/local/openssl \

threads zlib shared


4. 컴파일

# make

# make test


5. 설치

# make install



6. 세팅 

# vi /etc/ld.so.conf

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

  :

/usr/local/openssl/lib/  <-- 추가

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

# ldconfig



7. 확인

# strings /etc/ld.so.cache | grep openssl

/usr/local/openssl/lib/libssl.so.1.0.0

/usr/local/openssl/lib/libssl.so

libgnutls-openssl.so.13

/usr/lib/libgnutls-openssl.so.13

/usr/local/openssl/lib/libcrypto.so.1.0.0

/usr/local/openssl/lib/libcrypto.so



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

## openssh 설치 ##

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


-- 순서 --

0x1. openssh 소스다운로드

0x2. 이전 ssh 버전정보를 확인

0x3. 관련 라이브러리 설치

0x4. 압축해제

0x5. 환경설정

0x6. 컴파일

0x7. 설치

0x8. 이전 ssh 삭제

0x9. 세팅 

0xa. 데몬 시작 

0xb. 접속테스트


0x1. openssh 소스다운로드

# wget http://mirrors.nycbug.org/pub/OpenBSD/OpenSSH/portable/openssh-6.6p1.tar.gz


0x2. 이전 ssh 버전정보를 확인

# rpm -qa | grep openssh 

openssh-4.3p2-82.el5

openssh-server-4.3p2-82.el5

openssh-clients-4.3p2-82.el5



0x3. 관련 라이브러리 설치

- rpm -qa | grep pam으로 검색해서 없으면 설치한다.

# rpm -qa | grep pam 

# yum -y install pam-devel



0x4. 압축해제

# tar xzf openssh-6.6p1.tar.gz

# cd openssh-6.6p1


0x5. 환경설정

# vi version.h <-- 버전을 보안상 숨기고 싶다면 아래 파일을 수정한다



-- version.h --

//#define SSH_VERSION   "OpenSSH_6.6"

#define SSH_VERSION   "OpenSSH"

-- 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


0x6. 컴파일

# make


0x7. 설치 

# make install



0x8. 이전 ssh 삭제

- 데몬종료

- 접속을 유지하면서 패키지가 삭제된다.

# /etc/init.d/sshd stop   

# yum -y remove openssh openssh-server openssh-clients openssh-askpass



- OpenSSH 의 설정디렉토리 (수동삭제)

- 설정파일 디렉토리는 삭제가 안되므로 수동으로 삭제한다.

# rm -rf  /etc/ssh  


0x9. 세팅 

# cd contrib/redhat

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

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

# chkconfig --add sshd

# chkconfig --list sshd

sshd   0:off 1:off 2:on 3:on 4:on 5:on 6:off

                               ~~~~~~



# vi /etc/man.config



-- /etc/man.config --

  :

  :

MANPATH /usr/local/share/man           <-- 기존내용 (46 Line)

MANPATH /usr/X11R6/man                 <-- 기존내용 (47 Line)

MANPATH /usr/local/openssh/share/man   <-- 추가

-- /etc/man.config --



- 실행파일을 심볼릭 링크를 건다.

# 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


0xa. 데몬 시작 

# /etc/init.d/sshd start



0xb. 접속테스트

# nc localhost 22

SSH-2.0-OpenSSH_6.6  <-- 버전이 6.6의 최신버전이 나오면 성공 


(아까 버전을 숨겨서 버전이 나타나지 않는다)

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


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

OPENSSH-LAB> OpenSSH를 xinetd 서버로 구동해보자.


-- 순서 --

1. sshd 데몬 종료

2. sshd 스크립트 off 

3. ssh용 xinetd 설정파일 생성

4. xinetd 재시작

5. 확인

6. 접속


1. sshd 데몬 종료

# /etc/init.d/sshd stop


2. sshd 스크립트 off 

# chkconfig --list sshd

# chkconfig sshd off


3. ssh용 xinetd 설정파일 생성

# yum -y install xinetd

# vi /etc/xinetd.d/sshd



-- /etc/xinetd.d/sshd --

service ssh

{

  disable = no

  flags = REUSE

  socket_type = stream

  wait = no

  user = root

  server = /usr/sbin/sshd

  server_args = -i

  log_on_failure += USERID

}

-- /etc/xinetd.d/sshd --



4. xinetd 재시작

- 아래 명령어가 없다면 xinetd 패키지를 설치한다.

# /etc/init.d/xinetd restart 



5. 확인

# netstat -nltp|grep 22

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      5085/xinetd  



6. 접속

# nc localhost 22



- ssh를 xinetd 에서 Standalone 방식으로 띄우기 위해서는

  아래 내용을 실행하면 된다.

  간혹 업체가 ssh 를 xinetd 로 구동시키는 경우도 있을 수 있다.

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

# /etc/init.d/xinetd restart

# chkconfig sshd on

# /etc/init.d/sshd start

# netstat -nltp| grep 22

tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      17643/sshd


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


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

## openssh 명령어들 ##

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


# ls /usr/local/openssh/bin

scp  sftp  slogin  ssh  ssh-add  ssh-agent  ssh-keygen  ssh-keyscan


# ls /usr/local/openssh/sbin

sshd

# ls /usr/local/openssh/libexec/

sftp-server  ssh-keysign  ssh-pkcs11-helper


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


OPENSSH-LAB> ssh 로 접속을 했더니 Warning 메세지가 나온다면 ?


!!! 작업은 클라이언트에서 한다 !!!


공개키가 저장되는 파일 : $HOME/.ssh/known_hosts


- 원인 -

1. 서버의 공개키가 변경이된 것이다.

2. 공격(x)일 가능성이 있다.


- 해결방안 -

1. $HOME/.ssh/known_hosts 파일에 해당 호스트에 대한 키를 삭제한다.

2. $HOME/.ssh/known_hosts 파일을 삭제한다.


# ssh localhost

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!

Someone could be eavesdropping on you right now (man-in-the-middle attack)!

It is also possible that a host key has just been changed.

The fingerprint for the RSA key sent by the remote host is

00:f3:19:ee:36:f3:1f:fe:5c:ec:23:e0:c3:ba:3f:26.

Please contact your system administrator.

Add correct host key in /root/.ssh/known_hosts to get rid of this message.

Offending RSA key in /root/.ssh/known_hosts:1

RSA host key for localhost has changed and you have requested strict checking.

Host key verification failed.



# cd .ssh

# rm -f known_hosts  <-- 공개키가 담겨있는 파일을 삭제하고 접속한다.

# ssh localhost

The authenticity of host 'localhost (127.0.0.1)' can't be established.

ECDSA key fingerprint is e9:1f:5f:30:15:6d:e4:b0:1e:32:4d:ec:7c:79:ce:8c.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.




ex2)

- 서버의 공개키가 클라이언트의 저장된 공개키가 동일하므로 

  로그인이 나온다.

# ssh localhost

root@localhost's password:   ^C 취소


- 서버에서 키를 모두 삭제

# rm -f /etc/ssh/ssh_host_*

- sshd 서버를 재시작하면 키를 모두 생성한다. (이전키와 달라진다.)

# /etc/init.d/sshd restart


- 클라이언에서 서버로 접속

- 서버의 공개키가 클라이언트의 저장된 공개키와 다르므로 

  워닝창이 나오는 것이다.

# ssh localhost

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!

Someone could be eavesdropping on you right now (man-in-the-middle attack)!

It is also possible that a host key has just been changed.

The fingerprint for the ECDSA key sent by the remote host is

52:fe:d6:4b:af:46:e4:0f:f2:60:c5:ec:1b:42:5a:b9.

Please contact your system administrator.

Add correct host key in /root/.ssh/known_hosts to get rid of this message.

Offending ECDSA key in /root/.ssh/known_hosts:1

ECDSA host key for localhost has changed and you have requested strict checking.

Host key verification failed.


- 서버/클라이언트의 공개키가  서로 다르다는 것을 알 수 있다.


- 클라이어트에 저장된 공개키

# cat ~/.ssh/known_hosts 

localhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPk2rT0ocZ3clAnhUmfY0FU6/Fa+llyd0s5Lx+ZCRgJ6uNULkd5ng54EodlIeIaiNGlvmDCk3YEqkZaS+0R+7m4=


- 서버에 저장된 공개키

# cat /etc/ssh/ssh_host_ed25519_key.pub 

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMLfmd7F5zIbe76h16F3DsoyAE9VyX9i9BrVKXTxnZrd root@localhost.localdomain

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



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

## ssh 명령어 ##

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

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

OPENSSH-LAB> ssh 를 이용해서 서버에 접속하는 방법


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

|        |      |        |

| Client | ---> | Server |

|        |      |        |

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

  root      --->  sshuser


o 일반적인 접속방법: 

- 첫 번째 방법 : ssh sshuser@hostname 

- 두 번째 방법 : ssh -l sshuser hostname



o 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] [-Q protocol_feature]

           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]

           [-R [bind_address:]port:host:hostport] [-S ctl_path]

           [-W host:port] [-w local_tun[:remote_tun]]

           [user@]hostname [command]


o 서버로 접속하는 클라이언트 프로그램

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

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

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

**** # alias ssh='ssh -p2200'



Server# useradd sshuser; echo 1234 | passwd --stdin sshuser


- 접속방법 1 (이메일 형식으로 접속하는 방법)

Client# ssh sshuser@localhost 

sshuser@localhost's password:  <-- 1234 입력 

Server$  id

uid=525(sshuser) gid=525(sshuser) groups=525(sshuser) ...

Server$ exit


- 접속방법 2 (-l 옵션으로 접속하는 방법)

Client# ssh -l sshuser localhost

sshuser@localhost's password:  <-- 1234 입력 

Last login: Wed Apr 16 20:54:18 2014 from localhost.localdomain

Server$ 

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


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

OPENSSH-LAB> ssh 를 이용한 명령어 사용 


o 사용법: 

ssh sshuser@hostname  cmd

ssh -l sshuser hostname cmd


- ID/PW 인증이 정상적으로 성공하면 명령어(cmd) 가 성공적으로 실행된다. (단 로그인은 안된다.)

Client# ssh sshuser@localhost pwd    

sshuser@localhost's password:      <-- ID/PW 기반 인증

/home/sshuser


Client# ssh sshuser@localhost id

sshuser@localhost's password:      <-- ID/PW 기반 인증

uid=525(sshuser) gid=525(sshuser) groups=525(sshuser) ...


(Kali에서는 useradd [id]로 유저 생성 시 홈디렉터리가 자동으로 만들어 지지 않는다. -m 옵션을 주어야함)

(Kali에서 ssh 시작방법 -> # service ssh start)


Client# ssh sshuser@localhost top -b -n 1

sshuser@localhost's password: 

top - 16:26:18 up  6:45,  2 users,  load average: 0.52, 0.48, 0.45

Tasks:  51 total,   1 running,  50 sleeping,   0 stopped,   0 zombie

Cpu(s):  0.4%us,  1.5%sy,  0.0%ni, 97.3%id,  0.2%wa,  0.1%hi,  0.5%si,  0.0%st

Mem:    514868k total,   298552k used,   216316k free,    57368k buffers

Swap:  1048568k total,        0k used,  1048568k free,   201872k cached


  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND            

    1 root      15   0  2176  648  556 S  0.0  0.1   0:00.43 init               

    2 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00 migration/0        

    3 root      34  19     0    0    0 S  0.0  0.0   0:00.92 ksoftirqd/0        

  :

  :


# ssh sshuser@localhost bash

sshuser@localhost's password: 

ls

notice.txt

pwd

/home2/sshuser

id

uid=5029(sshuser) gid=5029(sshuser) groups=5029(sshuser)

exit

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


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

OPENSSH-LAB> ssh 를 이용한 top 실행하기 

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

|        |      |        |

| Client | ---> | Server |

|        |      |        |

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

  root     --->  user : topuser

                 port : 22


Server# useradd -s /usr/bin/top topuser

Server# echo 1234 | passwd --stdin topuser

Client# ssh topuser@localhost

                      <-- top 이 실행된다. 



Client# ssh -p 22 topuser@localhost   <-- -p <포트번호>  참고 : 포트번호가 22일때 생략 가능

topuser@localhost's password:


Client# ssh -p 22 -l topuser localhost  <-- topuser@localhost 와 동일

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


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

OPENSSH-LAB> 터널링 옵션 (-L -R) 사용하기


***** 숙제 ***** 

검색해보면 많이 나옴

방화벽 우회나 ssh이용 보안 강화에 사용하는 듯..