제목 : ssh 불법침입 탐지해서 block 시켜주는 스크립트
 
작성자 : 이선규 (neosky)  (neosky(at)smileserv.com, admin(at)nple.com,
http://seroot.com)
작성일 : 2010년 7월 8일



아래 내용은 외국 어느 고마운 분이 배포하고 있는 스크립트로,
ssh 불법침입을 탐지해서 block 시키는데 유용하게 쓰일 수 있어 소개하고자 합니다.


홈페이지 : http://bluedogsecurity.cyberinfo.se/sshblock2/Main.html


현재 SSH Block 2.2 버전이 공개되어 있고, 그 스크립트의 내용은 아래와 같습니다.
소스 그대로 긁어서 서버에 붙여넣어주고 실행권한만 주면 됨.

SunOS, Darwin, FreeBSD, OpenBSD, Linux OS에 적용가능하고,
Linux의 경우 /var/log/secure, /var/log/messages 에 남겨진 로그를 참조해서
/etc/hosts.deny 에 접근을 차단할 IP를 추가해줍니다.  (편리하죠? ㅎㅎ)

일정시간마다 모니터링해서 추가할 수 있도록 cron 설정해두면 좋습니다.




#!/bin/bash

################################################################################
#                                                                              #
#  Copyright (C) 2006 Jack-Benny Persson <jake@cyberinfo.se>                   #
#                                                                              #
#   This program is free software; you can redistribute it and/or modify       #
#   it under the terms of the GNU General Public License as published by       #
#   the Free Software Foundation; either version 2 of the License, or          #
#   (at your option) any later version.                                        #
#                                                                              #
#   This program is distributed in the hope that it will be useful,            #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of             #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              #
#   GNU General Public License for more details.                               #
#                                                                              #
#   You should have received a copy of the GNU General Public License          #
#   along with this program; if not, write to the Free Software                #
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  #
#                                                                              #
################################################################################

# SSH Block 2 - A script that blocks SSH probing hosts in /etc/hosts.deny
# This is version two of SSH Block, wich is a total re-write of the original
# code. This version should work on Linux, FreeBSD, Solaris and Mac OS X.
# Please read the README file for more information.

#If these users are trying to login via SSH, the host is instantly blocked.
#Be careful not to add users that normaly login via SSH here...
BLOCK_USERS=("root" "mysql" "nobody")

SLEEP_TIME=10
OS=`uname`

if [ "$OS" = "FreeBSD" ]; then
    DENYFILE="/etc/hosts.allow" #Both allow and deny in one file on FreeBSD
elif [ "$OS" != "FreeBSD" ]; then
    DENYFILE="/etc/hosts.deny" #The default way...
fi

if [ "$UID" -ne 0 ]; then
    echo "Must be run as root"
    exit 2
fi

#The default way...
print_ip()
{
    sort | uniq | sed -e 's/^/sshd : /' >> ${DENYFILE}
}

#The FreeBSD way...
print_ip_freebsd()
{
    sort | uniq | sed -e 's/^/sshd : /' | sed -e 's/$/ : deny/' >> \
    ${DENYFILE}
}

#Diffrent logfiles with diffrent syntax on diffrent systems...
SunOS_greplog()
{
    grep sshd /var/log/authlog | grep 'invalid user' \
    | awk '{print $15}' - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep \
    "Failed keyboard-interactive for $i from" \
    /var/log/authlog; done | awk '{print $14}' - | sort | uniq
}

FreeBSD_greplog()
{
    (grep 'Illegal user' /var/log/auth.log || \
    grep 'Invalid user' /var/log/auth.log) \
    | awk '{print $10}' - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep "Failed password for $i from" \
    /var/log/auth.log; done | awk '{print $11}' - | sort | uniq
}

OpenBSD_greplog()
{
    grep 'Invalid user' /var/log/authlog \
    | awk '{print $10}' - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep "Failed password for $i from" \
    /var/log/authlog; done | awk '{print $11}' - | sort | uniq
}

Linux_greplog()
{
    (grep '[Ii]nvalid user' /var/log/messages || \
    grep '[Ii]llegal user' /var/log/secure || \
    grep '[Ii]llegal user' /var/log/messages || \
    grep '[Ii]nvalid user' /var/log/secure) \
    | egrep -o '[0-9]{1,3}(\.[0-9]{1,3}){3}' - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep \
    "Authentication failure for $i from" \
    /var/log/messages; done | egrep -o '[0-9]{1,3}(\.[0-9]{1,3}){3}' \
    - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep "Failed password for $i from" \
    /var/log/messages; done | egrep -o '[0-9]{1,3}(\.[0-9]{1,3}){3}' \
    - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep \
    "Authentication failure for $i from" \
    /var/log/secure; done | egrep -o '[0-9]{1,3}(\.[0-9]{1,3}){3}' \
    - | sort | uniq
}

Darwin_greplog()
{
    grep sshd /var/log/system.log | grep 'illegal user' \
    | awk '{print $15}' - | sort | uniq

    for i in ${BLOCK_USERS[*]}; do grep \
    "Authentication failure for $i from" \
    /var/log/system.log; done |  - | awk '{print $13}' sort | uniq

}

SunOS_size()
{
    ls -l /var/log/authlog | awk '{print $5}'
}

Darwin_size()
{
    ls -l /var/log/system.log | awk '{print $5}'
}

FreeBSD_size()
{
    ls -l /var/log/auth.log | awk '{print $5}'
}

OpenBSD_size()
{
    ls -l /var/log/authlog | awk '{print $5}'
}

Linux_size()
{
    if [ -e /var/log/secure ] && [ -e /var/log/messages ]; then
        A=`ls -l /var/log/secure | awk '{print $5}'`
        B=`ls -l /var/log/messages | awk '{print $5}'`
        let C=A+B
        echo $C
    elif [ -e /var/log/secure ]; then
        ls -l /var/log/secure | awk '{print $5}'
    elif [ -e /var/log/messages ]; then
        ls -l /var/log/messages | awk '{print $5}'
    fi
}

touch ${DENYFILE}

#Check if we have run SSH Block before....
RUN_BEFORE=`grep -c "#BEGIN_SSHBLOCK" ${DENYFILE}`
if [ $RUN_BEFORE -gt 0 ]; then
    echo "/#BEGIN_SSHBLOCK/,/#END_SSHBLOCK/d|x" \
    | ex -s ${DENYFILE}
fi

OLD_SIZE=0

#Here we go!
(
while true
do
    case "$OS" in
        SunOS) SIZE=`SunOS_size` ;;
        Darwin) SIZE=`Darwin_size` ;;
        FreeBSD) SIZE=`FreeBSD_size` ;;
        OpenBSD) SIZE=`OpenBSD_size` ;;
        Linux) SIZE=`Linux_size` ;;
    esac
    if [ $OLD_SIZE -ne $SIZE ]; then

        BLOCK_EXIST=`grep -c "#BEGIN_SSHBLOCK" ${DENYFILE}`
        if [ $BLOCK_EXIST -gt 0 ]; then
            echo "/#BEGIN_SSHBLOCK/,/#END_SSHBLOCK/d|x" \
            | ex -s ${DENYFILE}
        fi

        echo "#BEGIN_SSHBLOCK" >> ${DENYFILE}
        case "$OS" in
            SunOS) SunOS_greplog | print_ip ;;
            FreeBSD) FreeBSD_greplog | print_ip_freebsd ;;
            OpenBSD) OpenBSD_greplog | print_ip ;;
            Linux) Linux_greplog | print_ip ;;
            Darwin) Darwin_greplog | print_ip ;;
        esac
        echo "#END_SSHBLOCK" >> ${DENYFILE}
        case "$OS" in
            SunOS) OLD_SIZE=`SunOS_size` ;;
            Darwin) OLD_SIZE=`Darwin_size` ;;
            FreeBSD) OLD_SIZE=`FreeBSD_size` ;;
            OpenBSD) OLD_SIZE=`OpenBSD_size` ;;
            Linux) OLD_SIZE=`Linux_size` ;;
        esac
        sleep ${SLEEP_TIME}
    else
        sleep ${SLEEP_TIME}
    fi
done
) 2> /dev/null &




사용자 삽입 이미지
▲ SSH Block 2 배포 사이트



2010/07/08 15:52 2010/07/08 15:52








마음튼튼 이 작성.

당신의 의견을 작성해 주세요.

[로그인][오픈아이디란?]
오픈아이디로만 댓글을 남길 수 있습니다


Putty를 이용해서 서버에 접속하다 보면
창을 여러개 띄워놓아야 하는 경우가 발생한다.

나중에는 어느 Putty창이 어떤 서버에 접속했는지
관리가 힘들어지는 상황이 발생하게 되는데...
(물론 아이피가 표시되어 찾을 수 있지만, 한 서버에 여럿 접속한 경우라면??)

이럴때 효과적으로 접속창을 관리할 수 있는 Putty Connection Manager를 써보는 건 어떨까?


1. 먼저 서버에 Putty 가 설치되어 있어야 한다.
    Putty 가 없다면 설치방법은 간단하니 아래 URL 에서 다운로드 받아 설치해주도록 한다.


    http://kldp.net/projects/iputty/


2. 자, 이제 puttycm 홈페이지로 이동하여 프로그램을 다운로드 받도록 한다.

   http://puttycm.free.fr/cms/


사용자 삽입 이미지

3. 설치마법사가 실행된다.
   특별히 설정해줘야할 사항은 아직 없으므로 NEXT로 넘어가도록 한다.

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지
 
4. 처음 Putty Connect Manager 를 실행하게 되면 Putty.exe 실행파일 위치를 물어보게 된다.
   설치된 곳에 Putty.exe 파일을 더블클릭하여 주도록 한다.ㅏ

사용자 삽입 이미지

사용자 삽입 이미지


5. PuTTY Connection Manager 초기화면이다.
   상단에 Protocol 부분이 실제 접속시 정보를 입력하는 곳이다.
   만약, TOOLBAR 가 보이지 않는다면, 상단바에서 오른쪽을 클릭해 Resotre Toolbars 메뉴를 선택하도록 한다.

사용자 삽입 이미지

6. 실제 여럿 연결해보면 아래와 같이 TAB으로 연결된 것을 확인할 수 있다.
    Database 기능을 이용하면 체계적인 서버연결에 대한 관리도 가능하다.

    좌측 DB 아이콘을 클릭하면 설정이 가능하다.  (설정화면 생략)
    설정하게 되면 우측 Connect Manager 라는 곳에
    관리서버 그룹 - SSH 연결 - SMS 서버라는 항목이 생성된게 보인다.
    이름은 본인이 지정가능하고, 설정후 변경도 가능하다.   

사용자 삽입 이미지
 
7. Database로 관리되고 있는 서버에 Login Macro 기능도 이용 가능하다.
   먼저, Enable post-login commands 를 체크해서 활성화 시킨다음
   Command 1 ~ Command 5 까지 명령을 써주면 로그인 후 해당 명령이 자동 실행하게 된다.

사용자 삽입 이미지


8. 실제 MACRO 기능을 이용해서 설정한 후 서버에 접속한 화면이다.
    로그인 ID, PW도 자동으로 입력되고, Command 1 ~ Command 3까지 입력한
    명령이 자동 실행된 것이 보인다.
  

사용자 삽입 이미지
 
이상, PuTTY Connection Manager 프로그램의 설치, 접속방법, 간단한 Database에서의 기능을 살펴보았다.
세부적인 기능은 각자 살펴보고 사용해보도록 하자 ^^

2010/03/25 11:31 2010/03/25 11:31








마음튼튼 이 작성.

당신의 의견을 작성해 주세요.

  1. Comment RSS : http://seroot.com/rss/comment/88
  2. 비밀방문자 2010/04/04 21:23  편집/삭제  댓글 작성  댓글 주소

    관리자만 볼 수 있는 댓글입니다.

    • neosky 2010/04/22 16:43  편집/삭제  댓글 주소

      제보해주셔서 감사합니다.
      웁스~~ 링크가.... 링크도 수정해두었습니다.

[로그인][오픈아이디란?]
오픈아이디로만 댓글을 남길 수 있습니다


Mindterm 3.2 (Java Applet SSH Client) 설치 및 사용방법

(주)스마일서브 고객기술지원팀 이선규 / neosky(at)smileserv.com



PC에 SSH 클라이언트 프로그램을 설치할 수 없거나,  설치가 귀챦은 경우
웹에서 SSH 서비스를 이용하고자 할 때 사용할 수 있는 프로그램을 소개하고자 합니다.

원본 글은 김정균님 블로그를 참조했으며, 그 주소는 링크와 같습니다.


설치방법

1. 라이센스
   개인사용자에 한하여 무료이며, 무료 버전에서는 설치된 서버로만 SSH 연결을 할 수 있습니다.
   유료 버전에서는 다른 서버로 직접 연결이 가능합니다.

2. 다운로드
    제품소개는 http://www.appgate.com/index/products/mindterm/ 에서 확인할 수 있으며,
    다운로드는 페이지 내 메뉴중 MindTerm download 에서 할 수 있다.  
    빌드할 일은 없으니 MindTerm application binaries (바이너리 버전)을 다운로드 받도록 합니다.

    2009년 2월 현재 최신 버전은 MindTerm 3.2 이며, 다음 URL로 직접 다운로드 가능하다.  
    http://www.appgate.com/downloads/MindTerm-3.2/mindterm_3.2-bin.zip

3. MindTerm은 Client 에 설치 되지 않고 Java Applet 으로 작동하므로
   웹 서비스를 할 수 있는 곳에 파일을 받고, 압축을 해제 합니다.

  shell > unzip mindterm_3.2-bin.zip
      Archive:  mindterm_3.2-bin.zip
         creating: mindterm-3.2/
        inflating: mindterm-3.2/LICENSE.txt
        inflating: mindterm-3.2/README.txt
        inflating: mindterm-3.2/THIRD_PARTY_SW.txt
        inflating: mindterm-3.2/Applet.txt
        inflating: mindterm-3.2/Settings.txt
        inflating: mindterm-3.2/RELEASE_NOTES.txt
        inflating: mindterm-3.2/mindterm.jar

4. 압축을 푼 후에 필요한 파일은 mindterm.jar 입니다. 
    압축이 풀린 디렉토리는 mindterm-3.2 에서 webssh 등 으로  변경합니다.
    그리고, Applet 을 호출 할 수 있는 문서를 (index.html 등) 다음과 같이 생성해 주도록 합니다.

   <!DOCTYPE html
       PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
   <head>
   <title>Mindterm WEB SSH Gate</title>
   <style type="text/css">
       h1 {
           font-size: 25px;
           font-family: tahoma, sans-serif;
           font-weight: bold;
           text-align: center;
           margin-top: 50px;
       }
   </style>
   </head>

   <body>
       <h1>Mindterm WEB SSH Gate</h1>
       <applet archive="mindterm.jar"
           code="com.mindbright.application.MindTerm.class"
           width="0" height="0">
           <param name="cabinets" value="mindterm.cab" />
           <param name="protocol" value="ssh2" />
           <param name="sepframe" value="true" />
           <param name="debug" value="true" />
           <param name="bg-color" value="black" />
           <param name="fg-color" value="white" />
           <param name="cursor-color" value="yellow" />
           <param name="encoding" value="euc-kr" / >
           <param name="font-name" value="Monospaced" / >
           <param name="exit-on-logout" value="true" / >
       </applet>

   </body>
   </html>

5. 웹 브라우징을 하는 PC에 Java JRE 또는 JVM이 반드시 설치되어 있어야 하므로, PC에 설치가 안되어 있다면
   다음 URL에서 JRE 6를 설치후 브라우저에서 접근해봅니다.

   * JRE 6 다운로드 : http://java.sun.com/javase/downloads/?intcmp=1281


6. 접근 결과 예)

사용자 삽입 이미지


사용자 삽입 이미지































ㄴ 로그인이 된 것을 확인 할 수 있다.

사용자 삽입 이미지































ㄴ 한글로 입력된 파일도 잘 보인다.

사용자 삽입 이미지





ㄴ 한글 입력에도 문제가 없다.

사용자 삽입 이미지






















ㄴ 터미널 설정은 Ctrl+Shift+T 또는  Settings -> Terminal 에서 가능하다.

2009/02/09 17:19 2009/02/09 17:19








마음튼튼 이 작성.

당신의 의견을 작성해 주세요.

[로그인][오픈아이디란?]
오픈아이디로만 댓글을 남길 수 있습니다