블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

« » 2024.5
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

공지사항

태그목록

최근에 올라온 글

'모의해킹 침해대응 전문가 과정'에 해당되는 글 99건

  1. 2016.08.03 20160803 SELinux
  2. 2016.08.03 20160803 소프트웨어 관리
  3. 2016.08.02 20160802 웹 방화벽
  4. 2016.08.02 20160802 Snort
  5. 2016.08.01 20160801 IDS
  6. 2016.08.01 20160801 TCP Wrapper
  7. 2016.08.01 20160801 NTP
  8. 2016.07.29 20160729 방화벽
  9. 2016.07.28 20160728 방화벽
  10. 2016.07.28 20160728 로그보안

 

 

 

SELinux(Secure Enhanced Linux)

 

 

 

 

 

 

 

1. 접근 통제(Access Control)

 

식별 및 인증된 사용자가 허가된 범위 내에서 시스템 내부정보에 대한 접근을 허용하는 기술적 방법을 접근제어(Access Control)라고 한다.

 

 

(1). 접근 통제의 유형

 

접근 통제(Access Control) 유형

임의적 접근 통제(Discretionary AC(DAC))- 신원기반 접근 통제(Identify-based)- 사용자기반 접근 통제(User-directed)- 혼합방식 접근 통제(Hybrid)

강제적 접근 통제(Mandatory AC(MAC))- 규칙기반 접근 통제(Rule-based)- 관리기반 접근 통제(Administratively)

비임의적 접근 통제(Non discretionary AC(NDAC))- 역할기반 접근 통제(Role-based)- 직무기반 접근 통제(Task-based)- 래티스 접근 통제(Lattice-based)

 

 

(2) 접근 통제 유형에 따른 대표적인 예

 

임의적 접근 통제 방식의 대표적인 예

# ls -l file1.txt

-rw-r--r-- 1 user01 user01 453 <시간> file1

 

강제적 접근 통제 방식의 대표적인 예

(주체의 비밀 취급 인가 레벨) (객체의 민감도 레이블)

Top Secret Top Secret

Secret Secret

Confidential Confidential

SBU

Unclassified

 

비임의적 접근 통제 방식의 대표적인 예

RBAC

사용자 <--> 역할 <-----> 허가 <--> 정보

 

 

 

-------------------------------------

이전의 웹서비스 Open 절차

() 웹 서비스 프로그램 설치

() 웹 서비스 설정

() 웹 서비스 기동

() 방화벽 서비스 Open

 

SELinux 체계의 웹서비스 Open 절차

() 웹 서비스 프로그램 설치

() 웹 서비스 설정

() 웹 서비스 기동

() 방화벽 서비스 Open

() SELinux 설정

-------------------------------------


[실습] SELinux Mode 전환

 

사용시스템

- CentOS 6.X(ids.example.com)

 

현재 SELinux Mode 확인

 

[참고] sestatus 명령어의 출력 결과 중 Current modeenforcing 아닌경우

# sestatus

SELinux status: disabled

# setenforce 1

SELinux status: disabled

# setenforce 0

SELinux status: disabled

# vi /etc/sysconfig/selinux

SELINUX=enforcing

# reboot

 

| enforcing/permissive | disabled |

|<--- setenforce ----> |

|<---------------- reboot ------->|

 

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing /* configuration in memory */

Mode from config file: enforcing /* configuration for /etc/sysconfig/selinux */

Policy version: 24

Policy from config file: targeted

 

# getenforce

Enforcing

 

enforcing Mode -> permissive Mode 전환

# setenforce

usage: setenforce [ Enforcing | Permissive | 1 | 0 ]

 

# setenforce 0 (# setenforce Permissive)

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: permissive

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# getenforce

Permissive

 

permissive Mode -> enforcing Mode 전환

# setenforce 1 (# setenforce Enforcing)

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# getenforce

Enforcing

 

 




[실습] SELinux 관련 패키지 설치

# yum -y install policycoreutils \

selinux-policy \

selinux-policy-targeted \

libselinux \

libselinux-utils \

libselinux-python

Loaded plugins: fastestmirror, refresh-packagekit, security

Loading mirror speeds from cached hostfile

* base: ftp.daum.net

* extras: ftp.daum.net

* updates: ftp.daum.net

base | 3.7 kB 00:00

extras | 3.3 kB 00:00

updates | 3.4 kB 00:00

updates/primary_db | 5.4 MB 00:01

Setting up Install Process

Resolving Dependencies

--> Running transaction check

---> Package libselinux.x86_64 0:2.0.94-5.3.el6 will be updated

---> Package libselinux.x86_64 0:2.0.94-5.3.el6_4.1 will be an update

---> Package libselinux-python.x86_64 0:2.0.94-5.3.el6 will be updated

---> Package libselinux-python.x86_64 0:2.0.94-5.3.el6_4.1 will be an update

---> Package libselinux-utils.x86_64 0:2.0.94-5.3.el6 will be updated

---> Package libselinux-utils.x86_64 0:2.0.94-5.3.el6_4.1 will be an update

---> Package policycoreutils.x86_64 0:2.0.83-19.30.el6 will be updated

---> Package policycoreutils.x86_64 0:2.0.83-19.39.el6 will be an update

---> Package selinux-policy.noarch 0:3.7.19-195.el6 will be updated

---> Package selinux-policy.noarch 0:3.7.19-231.el6_5.3 will be an update

---> Package selinux-policy-targeted.noarch 0:3.7.19-195.el6 will be updated

---> Package selinux-policy-targeted.noarch 0:3.7.19-231.el6_5.3 will be an update

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Updating:

libselinux x86_64 2.0.94-5.3.el6_4.1 base 108 k

libselinux-python x86_64 2.0.94-5.3.el6_4.1 base 202 k

libselinux-utils x86_64 2.0.94-5.3.el6_4.1 base 81 k

policycoreutils x86_64 2.0.83-19.39.el6 base 648 k

selinux-policy noarch 3.7.19-231.el6_5.3 updates 825 k

selinux-policy-targeted noarch 3.7.19-231.el6_5.3 updates 2.8 M

 

Transaction Summary

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

Upgrade 6 Package(s)

 

Total download size: 4.6 M

Downloading Packages:

(1/6): libselinux-2.0.94-5.3.el6_4.1.x86_64.rpm | 108 kB 00:00

(2/6): libselinux-python-2.0.94-5.3.el6_4.1.x86_64.rpm | 202 kB 00:00

(3/6): libselinux-utils-2.0.94-5.3.el6_4.1.x86_64.rpm | 81 kB 00:00

(4/6): policycoreutils-2.0.83-19.39.el6.x86_64.rpm | 648 kB 00:00

(5/6): selinux-policy-3.7.19-231.el6_5.3.noarch.rpm | 825 kB 00:00

(6/6): selinux-policy-targeted-3.7.19-231.el6_5.3.noarch.rpm | 2.8 MB 00:01

-----------------------------------------------------------------------------------------------------------------------------

Total 1.9 MB/s | 4.6 MB 00:02

warning: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY

Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

Importing GPG key 0xC105B9DE:

Userid : CentOS-6 Key (CentOS 6 Official Signing Key) <centos-6-key@centos.org>

Package: centos-release-6-4.el6.centos.10.x86_64 (@anaconda-CentOS-201303020151.x86_64/6.4)

From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

Running rpm_check_debug

Running Transaction Test

Transaction Test Succeeded

Running Transaction

Updating : libselinux-2.0.94-5.3.el6_4.1.x86_64 1/12

Updating : libselinux-utils-2.0.94-5.3.el6_4.1.x86_64 2/12

Updating : policycoreutils-2.0.83-19.39.el6.x86_64 3/12

Updating : selinux-policy-3.7.19-231.el6_5.3.noarch 4/12

Updating : selinux-policy-targeted-3.7.19-231.el6_5.3.noarch 5/12

Updating : libselinux-python-2.0.94-5.3.el6_4.1.x86_64 6/12

Cleanup : selinux-policy-targeted-3.7.19-195.el6.noarch 7/12

Cleanup : selinux-policy-3.7.19-195.el6.noarch 8/12

Cleanup : policycoreutils-2.0.83-19.30.el6.x86_64 9/12

Cleanup : libselinux-utils-2.0.94-5.3.el6.x86_64 10/12

Cleanup : libselinux-python-2.0.94-5.3.el6.x86_64 11/12

Cleanup : libselinux-2.0.94-5.3.el6.x86_64 12/12

Verifying : libselinux-python-2.0.94-5.3.el6_4.1.x86_64 1/12

Verifying : selinux-policy-3.7.19-231.el6_5.3.noarch 2/12

Verifying : selinux-policy-targeted-3.7.19-231.el6_5.3.noarch 3/12

Verifying : libselinux-2.0.94-5.3.el6_4.1.x86_64 4/12

Verifying : libselinux-utils-2.0.94-5.3.el6_4.1.x86_64 5/12

Verifying : policycoreutils-2.0.83-19.39.el6.x86_64 6/12

Verifying : libselinux-python-2.0.94-5.3.el6.x86_64 7/12

Verifying : libselinux-utils-2.0.94-5.3.el6.x86_64 8/12

Verifying : selinux-policy-3.7.19-195.el6.noarch 9/12

Verifying : selinux-policy-targeted-3.7.19-195.el6.noarch 10/12

Verifying : policycoreutils-2.0.83-19.30.el6.x86_64 11/12

Verifying : libselinux-2.0.94-5.3.el6.x86_64 12/12

 

Updated:

libselinux.x86_64 0:2.0.94-5.3.el6_4.1 libselinux-python.x86_64 0:2.0.94-5.3.el6_4.1

libselinux-utils.x86_64 0:2.0.94-5.3.el6_4.1 policycoreutils.x86_64 0:2.0.83-19.39.el6

selinux-policy.noarch 0:3.7.19-231.el6_5.3 selinux-policy-targeted.noarch 0:3.7.19-231.el6_5.3

 

Complete!

 

# yum -y install selinux-policy-mls \

setroubleshoot \

setroubleshoot-server \

setools-gui \

setools-console \

mcstrans \

policycoretuils-python \

policycoreutils-gui

Loaded plugins: fastestmirror, refresh-packagekit, security

Loading mirror speeds from cached hostfile

* base: ftp.daum.net

* extras: ftp.daum.net

* updates: ftp.daum.net

Setting up Install Process

No package policycoretuils-python available.

Resolving Dependencies

--> Running transaction check

---> Package mcstrans.x86_64 0:0.3.1-4.el6 will be installed

---> Package policycoreutils-gui.x86_64 0:2.0.83-19.39.el6 will be installed

--> Processing Dependency: policycoreutils-python = 2.0.83-19.39.el6 for package: policycoreutils-gui-2.0.83-19.39.el6.x86_64

--> Processing Dependency: gtkhtml2 for package: policycoreutils-gui-2.0.83-19.39.el6.x86_64

--> Processing Dependency: gnome-python2-gtkhtml2 for package: policycoreutils-gui-2.0.83-19.39.el6.x86_64

---> Package selinux-policy-mls.noarch 0:3.7.19-231.el6_5.3 will be installed

--> Processing Dependency: policycoreutils-newrole >= 2.0.78-1 for package: selinux-policy-mls-3.7.19-231.el6_5.3.noarch

---> Package setools-console.x86_64 0:3.3.7-4.el6 will be installed

--> Processing Dependency: setools-libs = 3.3.7-4.el6 for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libsefs.so.4(VERS_4.0)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libseaudit.so.4(VERS_4.1)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libqpol.so.1(VERS_1.5)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libqpol.so.1(VERS_1.2)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libpoldiff.so.1(VERS_1.3)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libpoldiff.so.1(VERS_1.2)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libapol.so.4(VERS_4.1)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libapol.so.4(VERS_4.0)(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libsefs.so.4()(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libseaudit.so.4()(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libqpol.so.1()(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libpoldiff.so.1()(64bit) for package: setools-console-3.3.7-4.el6.x86_64

--> Processing Dependency: libapol.so.4()(64bit) for package: setools-console-3.3.7-4.el6.x86_64

---> Package setools-gui.x86_64 0:3.3.7-4.el6 will be installed

--> Processing Dependency: setools-libs-tcl = 3.3.7-4.el6 for package: setools-gui-3.3.7-4.el6.x86_64

--> Processing Dependency: tk >= 8.4.9 for package: setools-gui-3.3.7-4.el6.x86_64

--> Processing Dependency: tcl >= 8.4.9 for package: setools-gui-3.3.7-4.el6.x86_64

--> Processing Dependency: bwidget >= 1.8 for package: setools-gui-3.3.7-4.el6.x86_64

---> Package setroubleshoot.x86_64 0:3.0.47-6.el6 will be installed

---> Package setroubleshoot-server.x86_64 0:3.0.47-6.el6 will be installed

--> Processing Dependency: setroubleshoot-plugins >= 3.0.14 for package: setroubleshoot-server-3.0.47-6.el6.x86_64

--> Processing Dependency: setools-libs-python >= 3.3.7-4 for package: setroubleshoot-server-3.0.47-6.el6.x86_64

--> Processing Dependency: audit-libs-python >= 1.2.6-3 for package: setroubleshoot-server-3.0.47-6.el6.x86_64

--> Processing Dependency: python-slip-dbus for package: setroubleshoot-server-3.0.47-6.el6.x86_64

--> Running transaction check

---> Package audit-libs-python.x86_64 0:2.2-4.el6_5 will be installed

--> Processing Dependency: audit-libs = 2.2-4.el6_5 for package: audit-libs-python-2.2-4.el6_5.x86_64

---> Package bwidget.noarch 0:1.8.0-5.1.el6 will be installed

---> Package gnome-python2-gtkhtml2.x86_64 0:2.25.3-20.el6 will be installed

---> Package gtkhtml2.x86_64 0:2.11.1-7.el6 will be installed

---> Package policycoreutils-newrole.x86_64 0:2.0.83-19.39.el6 will be installed

---> Package policycoreutils-python.x86_64 0:2.0.83-19.39.el6 will be installed

--> Processing Dependency: libsemanage-python >= 2.0.43-4 for package: policycoreutils-python-2.0.83-19.39.el6.x86_64

--> Processing Dependency: libcgroup for package: policycoreutils-python-2.0.83-19.39.el6.x86_64

---> Package python-slip-dbus.noarch 0:0.2.20-1.el6_2 will be installed

--> Processing Dependency: python-decorator for package: python-slip-dbus-0.2.20-1.el6_2.noarch

---> Package setools-libs.x86_64 0:3.3.7-4.el6 will be installed

---> Package setools-libs-python.x86_64 0:3.3.7-4.el6 will be installed

---> Package setools-libs-tcl.x86_64 0:3.3.7-4.el6 will be installed

---> Package setroubleshoot-plugins.noarch 0:3.0.40-2.el6 will be installed

---> Package tcl.x86_64 1:8.5.7-6.el6 will be installed

---> Package tk.x86_64 1:8.5.7-5.el6 will be installed

--> Running transaction check

---> Package audit-libs.x86_64 0:2.2-2.el6 will be updated

--> Processing Dependency: audit-libs = 2.2-2.el6 for package: audit-2.2-2.el6.x86_64

---> Package audit-libs.x86_64 0:2.2-4.el6_5 will be an update

---> Package libcgroup.x86_64 0:0.40.rc1-6.el6_5.1 will be installed

---> Package libsemanage-python.x86_64 0:2.0.43-4.2.el6 will be installed

---> Package python-decorator.noarch 0:3.0.1-3.1.el6 will be installed

--> Running transaction check

---> Package audit.x86_64 0:2.2-2.el6 will be updated

---> Package audit.x86_64 0:2.2-4.el6_5 will be an update

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Installing:

mcstrans x86_64 0.3.1-4.el6 base 85 k

policycoreutils-gui x86_64 2.0.83-19.39.el6 base 209 k

selinux-policy-mls noarch 3.7.19-231.el6_5.3 updates 2.3 M

setools-console x86_64 3.3.7-4.el6 base 328 k

setools-gui x86_64 3.3.7-4.el6 base 242 k

setroubleshoot x86_64 3.0.47-6.el6 base 118 k

setroubleshoot-server x86_64 3.0.47-6.el6 base 1.3 M

Installing for dependencies:

audit-libs-python x86_64 2.2-4.el6_5 updates 59 k

bwidget noarch 1.8.0-5.1.el6 base 166 k

gnome-python2-gtkhtml2 x86_64 2.25.3-20.el6 base 22 k

gtkhtml2 x86_64 2.11.1-7.el6 base 154 k

libcgroup x86_64 0.40.rc1-6.el6_5.1 updates 126 k

libsemanage-python x86_64 2.0.43-4.2.el6 base 81 k

policycoreutils-newrole x86_64 2.0.83-19.39.el6 base 112 k

policycoreutils-python x86_64 2.0.83-19.39.el6 base 343 k

python-decorator noarch 3.0.1-3.1.el6 base 14 k

python-slip-dbus noarch 0.2.20-1.el6_2 base 30 k

setools-libs x86_64 3.3.7-4.el6 base 400 k

setools-libs-python x86_64 3.3.7-4.el6 base 222 k

setools-libs-tcl x86_64 3.3.7-4.el6 base 197 k

setroubleshoot-plugins noarch 3.0.40-2.el6 base 506 k

tcl x86_64 1:8.5.7-6.el6 base 1.9 M

tk x86_64 1:8.5.7-5.el6 base 1.4 M

Updating for dependencies:

audit x86_64 2.2-4.el6_5 updates 225 k

audit-libs x86_64 2.2-4.el6_5 updates 60 k

 

Transaction Summary

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

Install 23 Package(s)

Upgrade 2 Package(s)

 

Total download size: 11 M

Downloading Packages:

(1/25): audit-2.2-4.el6_5.x86_64.rpm | 225 kB 00:00

(2/25): audit-libs-2.2-4.el6_5.x86_64.rpm | 60 kB 00:00

(3/25): audit-libs-python-2.2-4.el6_5.x86_64.rpm | 59 kB 00:00

(4/25): bwidget-1.8.0-5.1.el6.noarch.rpm | 166 kB 00:00

(5/25): gnome-python2-gtkhtml2-2.25.3-20.el6.x86_64.rpm | 22 kB 00:00

(6/25): gtkhtml2-2.11.1-7.el6.x86_64.rpm | 154 kB 00:00

(7/25): libcgroup-0.40.rc1-6.el6_5.1.x86_64.rpm | 126 kB 00:00

(8/25): libsemanage-python-2.0.43-4.2.el6.x86_64.rpm | 81 kB 00:00

(9/25): mcstrans-0.3.1-4.el6.x86_64.rpm | 85 kB 00:00

(10/25): policycoreutils-gui-2.0.83-19.39.el6.x86_64.rpm | 209 kB 00:00

(11/25): policycoreutils-newrole-2.0.83-19.39.el6.x86_64.rp | 112 kB 00:00

(12/25): policycoreutils-python-2.0.83-19.39.el6.x86_64.rpm | 343 kB 00:00

(13/25): python-decorator-3.0.1-3.1.el6.noarch.rpm | 14 kB 00:00

(14/25): python-slip-dbus-0.2.20-1.el6_2.noarch.rpm | 30 kB 00:00

(15/25): selinux-policy-mls-3.7.19-231.el6_5.3.noarch.rpm | 2.3 MB 00:00

(16/25): setools-console-3.3.7-4.el6.x86_64.rpm | 328 kB 00:00

(17/25): setools-gui-3.3.7-4.el6.x86_64.rpm | 242 kB 00:00

(18/25): setools-libs-3.3.7-4.el6.x86_64.rpm | 400 kB 00:00

(19/25): setools-libs-python-3.3.7-4.el6.x86_64.rpm | 222 kB 00:00

(20/25): setools-libs-tcl-3.3.7-4.el6.x86_64.rpm | 197 kB 00:00

(21/25): setroubleshoot-3.0.47-6.el6.x86_64.rpm | 118 kB 00:00

(22/25): setroubleshoot-plugins-3.0.40-2.el6.noarch.rpm | 506 kB 00:00

(23/25): setroubleshoot-server-3.0.47-6.el6.x86_64.rpm | 1.3 MB 00:00

(24/25): tcl-8.5.7-6.el6.x86_64.rpm | 1.9 MB 00:00

(25/25): tk-8.5.7-5.el6.x86_64.rpm | 1.4 MB 00:00

-----------------------------------------------------------------------------------

Total 1.8 MB/s | 11 MB 00:05

Running rpm_check_debug

Running Transaction Test

Transaction Test Succeeded

Running Transaction

Updating : audit-libs-2.2-4.el6_5.x86_64 1/27

Installing : setools-libs-3.3.7-4.el6.x86_64 2/27

Installing : 1:tcl-8.5.7-6.el6.x86_64 3/27

Installing : 1:tk-8.5.7-5.el6.x86_64 4/27

Installing : setools-libs-python-3.3.7-4.el6.x86_64 5/27

Installing : audit-libs-python-2.2-4.el6_5.x86_64 6/27

Installing : gtkhtml2-2.11.1-7.el6.x86_64 7/27

Installing : gnome-python2-gtkhtml2-2.25.3-20.el6.x86_64 8/27

Installing : bwidget-1.8.0-5.1.el6.noarch 9/27

Installing : setools-libs-tcl-3.3.7-4.el6.x86_64 10/27

Installing : setools-console-3.3.7-4.el6.x86_64 11/27

Updating : audit-2.2-4.el6_5.x86_64 12/27

Installing : policycoreutils-newrole-2.0.83-19.39.el6.x86_64 13/27

Installing : python-decorator-3.0.1-3.1.el6.noarch 14/27

Installing : python-slip-dbus-0.2.20-1.el6_2.noarch 15/27

Installing : libsemanage-python-2.0.43-4.2.el6.x86_64 16/27

Installing : mcstrans-0.3.1-4.el6.x86_64 17/27

Installing : libcgroup-0.40.rc1-6.el6_5.1.x86_64 18/27

Installing : policycoreutils-python-2.0.83-19.39.el6.x86_64 19/27

Installing : setroubleshoot-plugins-3.0.40-2.el6.noarch 20/27

Installing : setroubleshoot-server-3.0.47-6.el6.x86_64 21/27

Installing : setroubleshoot-3.0.47-6.el6.x86_64 22/27

Installing : policycoreutils-gui-2.0.83-19.39.el6.x86_64 23/27

Installing : selinux-policy-mls-3.7.19-231.el6_5.3.noarch 24/27

Installing : setools-gui-3.3.7-4.el6.x86_64 25/27

Cleanup : audit-2.2-2.el6.x86_64 26/27

Cleanup : audit-libs-2.2-2.el6.x86_64 27/27

Verifying : setroubleshoot-server-3.0.47-6.el6.x86_64 1/27

Verifying : setools-console-3.3.7-4.el6.x86_64 2/27

Verifying : setools-libs-python-3.3.7-4.el6.x86_64 3/27

Verifying : 1:tcl-8.5.7-6.el6.x86_64 4/27

Verifying : libcgroup-0.40.rc1-6.el6_5.1.x86_64 5/27

Verifying : setools-libs-3.3.7-4.el6.x86_64 6/27

Verifying : python-slip-dbus-0.2.20-1.el6_2.noarch 7/27

Verifying : policycoreutils-gui-2.0.83-19.39.el6.x86_64 8/27

Verifying : audit-libs-python-2.2-4.el6_5.x86_64 9/27

Verifying : setroubleshoot-3.0.47-6.el6.x86_64 10/27

Verifying : audit-2.2-4.el6_5.x86_64 11/27

Verifying : setroubleshoot-plugins-3.0.40-2.el6.noarch 12/27

Verifying : gnome-python2-gtkhtml2-2.25.3-20.el6.x86_64 13/27

Verifying : policycoreutils-python-2.0.83-19.39.el6.x86_64 14/27

Verifying : setools-gui-3.3.7-4.el6.x86_64 15/27

Verifying : selinux-policy-mls-3.7.19-231.el6_5.3.noarch 16/27

Verifying : gtkhtml2-2.11.1-7.el6.x86_64 17/27

Verifying : bwidget-1.8.0-5.1.el6.noarch 18/27

Verifying : setools-libs-tcl-3.3.7-4.el6.x86_64 19/27

Verifying : mcstrans-0.3.1-4.el6.x86_64 20/27

Verifying : audit-libs-2.2-4.el6_5.x86_64 21/27

Verifying : 1:tk-8.5.7-5.el6.x86_64 22/27

Verifying : libsemanage-python-2.0.43-4.2.el6.x86_64 23/27

Verifying : python-decorator-3.0.1-3.1.el6.noarch 24/27

Verifying : policycoreutils-newrole-2.0.83-19.39.el6.x86_64 25/27

Verifying : audit-2.2-2.el6.x86_64 26/27

Verifying : audit-libs-2.2-2.el6.x86_64 27/27

 

Installed:

mcstrans.x86_64 0:0.3.1-4.el6

policycoreutils-gui.x86_64 0:2.0.83-19.39.el6

selinux-policy-mls.noarch 0:3.7.19-231.el6_5.3

setools-console.x86_64 0:3.3.7-4.el6

setools-gui.x86_64 0:3.3.7-4.el6

setroubleshoot.x86_64 0:3.0.47-6.el6

setroubleshoot-server.x86_64 0:3.0.47-6.el6

 

Dependency Installed:

audit-libs-python.x86_64 0:2.2-4.el6_5

bwidget.noarch 0:1.8.0-5.1.el6

gnome-python2-gtkhtml2.x86_64 0:2.25.3-20.el6

gtkhtml2.x86_64 0:2.11.1-7.el6

libcgroup.x86_64 0:0.40.rc1-6.el6_5.1

libsemanage-python.x86_64 0:2.0.43-4.2.el6

policycoreutils-newrole.x86_64 0:2.0.83-19.39.el6

policycoreutils-python.x86_64 0:2.0.83-19.39.el6

python-decorator.noarch 0:3.0.1-3.1.el6

python-slip-dbus.noarch 0:0.2.20-1.el6_2

setools-libs.x86_64 0:3.3.7-4.el6

setools-libs-python.x86_64 0:3.3.7-4.el6

setools-libs-tcl.x86_64 0:3.3.7-4.el6

setroubleshoot-plugins.noarch 0:3.0.40-2.el6

tcl.x86_64 1:8.5.7-6.el6

tk.x86_64 1:8.5.7-5.el6

 

Dependency Updated:

audit.x86_64 0:2.2-4.el6_5 audit-libs.x86_64 0:2.2-4.el6_5

 

Complete!

 

 



[실습] audit/rsyslog 서비스 on/off

 

audit tail(감사 추적) --> auditd

 

# chkconfig auditd on (# service auditd restart)

# chkconfig rsyslog on (# service rsyslog restart)

 

# service auditd status

auditd (pid 5031)를 실행하고 있습니다.

 

# service rsyslog status

rsyslogd (pid 1768)를 실행하고 있습니다..

 

# tail -f /var/log/audit/audit.log (# grep denied /var/log/audit/audit.log)

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

type=LOGIN msg=audit(1412904601.114:34683): pid=9446 uid=0 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 old auid=4294967295 new auid=0 old ses=4294967295 new ses=11

type=USER_START msg=audit(1412904601.121:34684): user pid=9446 uid=0 auid=0 ses=11 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='op=PAM:session_open acct="root" exe="/usr/sbin/crond" hostname=? addr=? terminal=cron res=success'

type=CRED_DISP msg=audit(1412904601.158:34685): user pid=9446 uid=0 auid=0 ses=11 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='op=PAM:setcred acct="root" exe="/usr/sbin/crond" hostname=? addr=? terminal=cron res=success'

type=USER_END msg=audit(1412904601.159:34686): user pid=9446 uid=0 auid=0 ses=11 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='op=PAM:session_close acct="root" exe="/usr/sbin/crond" hostname=? addr=? terminal=cron res=success'

type=AVC msg=audit(1412910127.774:34815): avc: denied { search } for pid=11591 comm="vsftpd" name="home" dev=dm-0 ino=262145 scontext=unconfined_u:system_r:ftpd_t:s0-s0:c0.c1023 tcontext=system_u:object_r:home_root_t:s0 tclass=dir

<CTRL + C>

-> 아직은 설정을 한 후에 테스트를 하지 않아서 denied 되는 메세지가 audit.log 파일에 쌓여 있지

는 않을 것이다.

 

 

 

[실습] SELinux Mode 전환 및 확인

# cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.

# SELINUX= can take one of these three values:

# enforcing - SELinux security policy is enforced.

# permissive - SELinux prints warnings instead of enforcing.

# disabled - No SELinux policy is loaded.

SELINUX=enforcing

# SELINUXTYPE= can take one of these two values:

# targeted - Targeted processes are protected,

# mls - Multi Level Security protection.

SELINUXTYPE=targeted

 

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing

Mode from config file: enforcing /* /etc/sysconfig/selinux */

Policy version: 24

Policy from config file: targeted

-> permissive

 

# setenforce

usage: setenforce [ Enforcing | Permissive | 1 | 0 ]

 

# setenforce 0 = # setenforce permissive

# setenforce 1 = # setenforce enforcing

 

 

 

# setenforce 0

# cat /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.

# SELINUX= can take one of these three values:

# enforcing - SELinux security policy is enforced.

# permissive - SELinux prints warnings instead of enforcing.

# disabled - No SELinux policy is loaded.

SELINUX=enforcing

# SELINUXTYPE= can take one of these two values:

# targeted - Targeted processes are protected,

# mls - Multi Level Security protection.

SELINUXTYPE=targeted

 

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: permissive

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# getenforce

Permissive

 

# setenforce 1

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# setenforce 0

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: permissive

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

 

 

 

 

 

 


[실습] SELinux 기본 명령어 사용법 실습

 

# semanage boolean -l | grep allow_ftpd

# getsebool -a

# getsebool allow_ftpd_full_access

# setsebool allow_ftpd_full_access on

 

# semanage boolean

/usr/sbin/semanage:

semanage [ -S store ] -i [ input_file | - ]

semanage [ -S store ] -o [ output_file | - ]

 

semanage login -{a|d|m|l|D|E} [-nrs] login_name | %groupname

semanage user -{a|d|m|l|D|E} [-LnrRP] selinux_name

semanage port -{a|d|m|l|D|E} [-nrt] [ -p proto ] port | port_range

semanage interface -{a|d|m|l|D|E} [-nrt] interface_spec

semanage module -{a|d|m} [--enable|--disable] module

semanage node -{a|d|m|l|D|E} [-nrt] [ -p protocol ] [-M netmask] addr

semanage fcontext -{a|d|m|l|D|E} [-efnrst] file_spec

semanage boolean -{d|l|m} [--on|--off|-1|-0] -F boolean | boolean_file

semanage permissive -{d|a|l} [-n] type

semanage dontaudit [ on | off ]

 

Primary Options:

 

-a, --add Add a OBJECT record NAME

-d, --delete Delete a OBJECT record NAME

-m, --modify Modify a OBJECT record NAME

-i, --input Input multiple semange commands in a transaction

-o, --output Output current customizations as semange commands

-l, --list List the OBJECTS

-E, --extract extract customizable commands

-C, --locallist List OBJECTS local customizations

-D, --deleteall Remove all OBJECTS local customizations

 

-h, --help Display this message

-n, --noheading Do not print heading when listing OBJECTS

-S, --store Select and alternate SELinux store to manage

 

Object-specific Options (see above):

 

-f, --ftype File Type of OBJECT

"" (all files)

-- (regular file)

-d (directory)

-c (character device)

-b (block device)

-s (socket)

-l (symbolic link)

-p (named pipe)

 

-F, --file Treat target as an input file for command, change multiple settings

-p, --proto Port protocol (tcp or udp) or internet protocol version of node (ipv4 or

ipv6)

-M, --mask Netmask

-e, --equal Substitue source path for dest path when labeling

-P, --prefix Prefix for home directory labeling

-L, --level Default SELinux Level (MLS/MCS Systems only)

-R, --roles SELinux Roles (ex: "sysadm_r staff_r")

-s, --seuser SELinux User Name

-t, --type SELinux Type for the object

-r, --range MLS/MCS Security Range (MLS/MCS Systems only)

--enable Enable a module

--disable Disable a module

 

 

 

 

# semanage boolean -l

SELinux boolean State Default Description

 

ftp_home_dir (off , off) Allow ftp to read and write files in the user home directories

smartmon_3ware (off , off) Enable additional permissions needed to support devices on 3ware controllers.

xdm_sysadm_login (off , off) Allow xdm logins as sysadm

xen_use_nfs (off , off) Allow xen to manage nfs files

mozilla_read_content (off , off) Control mozilla content access

ssh_chroot_rw_homedirs (off , off) Allow ssh with chroot env to read and write files in the user home directories

postgresql_can_rsync (off , off) Allow postgresql to use ssh and rsync for point-in-time recovery

allow_console_login (on , on) Allow direct login to the console device. Required for System 390

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

httpd_setrlimit (off , off) Allow httpd daemon to change system limits

squid_connect_any (on , on) Allow squid to connect to all ports, not just HTTP, FTP, and Gopher ports.

virt_use_samba (off , off) Allow virt to manage cifs files

cluster_use_execmem (off , off) Allow cluster administrative cluster domains memcheck-amd64- to use executable memory

named_write_master_zones (off , off) Allow BIND to write the master zone files. Generally this is used for dynamic DNS or zone transfers.

exim_manage_user_files (off , off) Allow exim to create, read, write, and delete unprivileged user files.

logging_syslog_can_read_tmp (off , off) Allow syslogd daemon to read user tmp content

cron_can_relabel (off , off) Allow system cron jobs to relabel filesystem for restoring file contexts.

git_system_use_cifs (off , off) Determine whether Git system daemon can access cifs file systems.

 

# getsebool

usage: getsebool -a or getsebool boolean...

 

# getsebool -a

abrt_anon_write --> off

abrt_handle_event --> off

allow_console_login --> on

allow_cvs_read_shadow --> off

allow_daemons_dump_core --> on

allow_daemons_use_tcp_wrapper --> off

allow_daemons_use_tty --> on

allow_domain_fd_use --> on

allow_execheap --> off

allow_execmem --> on

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

virt_use_sysfs --> on

virt_use_usb --> on

virt_use_xserver --> off

webadm_manage_user_files --> off

webadm_read_user_files --> off

wine_mmap_zero_ignore --> off

xdm_exec_bootloader --> off

xdm_sysadm_login --> off

xen_use_nfs --> off

xguest_connect_network --> on

xguest_mount_media --> on

xguest_use_bluetooth --> on

xserver_object_manager --> off

zabbix_can_network --> off

 

# getsebool allow_console_login

allow_console_login --> on

 

# semanage boolean -l | grep ftp

ftp_home_dir (off , off) Allow ftp to read and write files in the user home directories

allow_ftpd_full_access (off , off) Allow ftp servers to login to local users and read/write all files on the system, governed by DAC.

allow_ftpd_use_cifs (off , off) Allow ftp servers to use cifs used for public file transfer services.

allow_ftpd_use_nfs (off , off) Allow ftp servers to use nfs used for public file transfer services.

allow_ftpd_anon_write (off , off) Allow ftp servers to upload files, used for public file transfer services. Directories must be labeled public_content_rw_t.

tftp_anon_write (off , off) Allow tftp to modify public files used for public file transfer services.

ftpd_use_passive_mode (off , off) Allow ftp servers to use bind to all unreserved ports for passive mode

tftp_use_cifs (off , off) Allow tftp to read from a CIFS store for public file transfer services.

tftp_use_nfs (off , off) Allow tftp to read from a NFS store for public file transfer services.

ftpd_use_fusefs (off , off) Allow ftpd to use ntfs/fusefs volumes.

ftpd_connect_db (off , off) Allow ftp servers to use connect to mysql database

httpd_enable_ftp_server (off , off) Allow httpd to act as a FTP server by listening on the ftp port.

 

# getsebool allow_ftpd_full_access

allow_ftpd_full_access --> off

 

# setsebool allow_ftpd_full_access on

# getsebool allow_ftpd_full_access

allow_ftpd_full_access --> on

 

 

 

# semanage boolean -l | grep allow_ftpd

allow_ftpd_full_access (on , off) Allow ftp servers to login to local users and read/write all files on the system, governed by DAC.

allow_ftpd_use_cifs (off , off) Allow ftp servers to use cifs used for public file transfer services.

allow_ftpd_use_nfs (off , off) Allow ftp servers to use nfs used for public file transfer services.

allow_ftpd_anon_write (off , off) Allow ftp servers to upload files, used for public file transfer services. Directories must be labeled public_content_rw_t

 

 

 

[실습] SELinux 설정 테스트(FTP Server/FTP Client)

 

사용시스템

- id.example.com(192.168.20.203)

- kaliLinux(192.168.20.50)

 

 

실습 시나리오

CentOS 6.X Kali Linux

(192.168.20.203) (192.168.20.50)

----- SELinux Server ---- ------ Client ------

 

FTP Server FTP Client

# ftp <서버 IP>

 

------------------------- -------------------

 

(on FTP Server) CentOS 6.X

 

(필요하면 명령어 수행)

# cat /etc/resolv.conf /* 외부 DNS 서버 지정 */

# yum -y install ftp vsftpd /* FTP 서버/클라이언트 패키지 설치 */

# sed -i 's/^root/#root/' /etc/vsftpd/ftpusers /* root 사용자 허용 */

# sed -i 's/^root/#root/' /etc/vsftpd/user_list /* root 사용자 허용 */

# chkconfig vsftpd on /* (부팅) FTP 서비스 on */

# service vsftpd start /* (현재) FTP 서비스 start */

# chkconfig iptables off /* (부팅) 방화벽 서비스 off */

# service iptables stop /* (현재) 방화벽 서비스 stop */

 

# setsebool allow_ftpd_full_access off

# getsebool allow_ftpd_full_access

allow_ftpd_full_access --> off

 

# tail -f /var/log/audit/audit.log

-> 모니터링한다.

 

 

(on FTP Client) KaliLinux

 

(전제조건) user01 사용자 추가

(CentOS 6.X)# useradd user01

# echo user01 | passwd --stdin user01

 

(KaliLinux) # useradd -m -s /bin/bash user01

# echo user01 | passwd --stdin user01

 

# su - user01

$ dd if=/dev/zero of=test.txt bs=1M count=5

5+0 records in

5+0 records out

5242880 bytes (5.2 MB) copied, 0.0127335 s, 412 MB/s

 

# ftp 192.168.20.203 /* KaliLinux(192.168.20.50) -> ids.example.com(192.168.20.203) */

Connected to 192.168.10.250.

220 (vsFTPd 2.2.2)

Name (192.168.10.250:root): user01

331 Please specify the password.

Password: (user01 사용자 암호 입력)

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> ls

200 PORT command successful. Consider using PASV.

150 Here comes the directory listing.

226 Directory send OK.

ftp> passive

Passive mode on.

ftp> put test.txt /* KaliLinux(현재DIR/test.txt) -> IDS(/home/user01/test.txt) */

local: test.txt remote: test.txt

227 Entering Passive Mode (192,168,10,250,214,87).

150 Ok to send data.

226 Transfer complete.

5242880 bytes sent in 0.11 secs (44618.3 kB/s)

ftp> lcd /tmp

Local directory now /tmp

ftp> get test.txt /* IDS(/home/user01/test.txt) -> KaliLinux(/tmp/test.txt) */

local: test.txt remote: test.txt

227 Entering Passive Mode (192,168,10,250,254,215).

150 Opening BINARY mode data connection for test.txt (5242880 bytes).

226 Transfer complete.

5242880 bytes received in 0.08 secs (61780.5 kB/s)

ftp> quit

221 Goodbye

 

$

(on FTP Server) CentOS 6.X

# tail -f /var/log/audit/audit.log

type=USER_AUTH msg=audit(1412947954.776:104): user pid=3831 uid=0 auid=0 ses=1 subj=unconfined_u:system_r:ftpd_t:s0-s0:c0.c1023 msg='op=PAM:authentication acct="user01" exe="/usr/sbin/vsftpd" hostname=192.168.10.100 addr=192.168.10.100 terminal=ftp res=success'

type=USER_ACCT msg=audit(1412947954.780:105): user pid=3831 uid=0 auid=0 ses=1 subj=unconfined_u:system_r:ftpd_t:s0-s0:c0.c1023 msg='op=PAM:accounting acct="user01" exe="/usr/sbin/vsftpd" hostname=192.168.10.100 addr=192.168.10.100 terminal=ftp res=success'

type=CRED_ACQ msg=audit(1412947954.780:106): user pid=3831 uid=0 auid=0 ses=1 subj=unconfined_u:system_r:ftpd_t:s0-s0:c0.c1023 msg='op=PAM:setcred acct="user01" exe="/usr/sbin/vsftpd" hostname=192.168.10.100 addr=192.168.10.100 terminal=ftp res=success'

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

-> 모니터링 윈도우에 위와 같은 메세지가 출력된다.

-> 메세지는 출력되지만 서비스가 안되는 것은 아니다.

 

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: permissive

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# setenforce 1

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

# getsebool allow_ftpd_full_access

allow_ftpd_full_access --> off

 

 

(on FTP Client) KaliLinux

$ ftp 192.168.20.203

Connected to 192.168.10.250.

220 (vsFTPd 2.2.2)

Name (192.168.10.250:root): user01

331 Please specify the password.

Password: (user01 사용자의 암호 입력)

500 OOPS: cannot change directory:/home/user01

Login failed.

ftp> quit

421 Service not available, remote server has closed connection

-> root 사용자도 접근되지 않음

 

$ ftp 192.168.20.203

Connected to 192.168.10.250.

220 (vsFTPd 2.2.2)

Name (192.168.10.250:root): anonymous

331 Please specify the password.

Password: (id@naver.com)

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

 

(필요하면 명령어 수행)

(192.168.20.203) CentOS 6.X

# cd /var/ftp/pub

# cp /etc/passwd /var/ftp/pub/test.txt

 

ftp> cd pub

250 Directory successfully changed.

ftp> dir

200 PORT command successful. Consider using PASV.

150 Here comes the directory listing.

-rw-r--r-- 1 0 0 1571 Oct 10 02:39 test.txt

226 Directory send OK.

ftp> mget test.txt

mget test.txt? y

200 PORT command successful. Consider using PASV.

150 Opening BINARY mode data connection for test.txt (1571 bytes).

226 Transfer complete.

1571 bytes received in 0.00 secs (2293.2 kB/s)

ftp> quit

221 Goodbye.

 

 

(on FTP Server) CentOS 6.X

# setsebool allow_ftpd_full_access on

# getsebool allow_ftpd_full_access

allow_ftpd_full_access --> on

 

# sestatus

SELinux status: enabled

SELinuxfs mount: /selinux

Current mode: enforcing

Mode from config file: enforcing

Policy version: 24

Policy from config file: targeted

 

 

(on FTP Client) KaliLinux

# ftp 192.168.20.203

$ ftp 192.168.10.250

Connected to 192.168.10.250.

220 (vsFTPd 2.2.2)

Name (192.168.10.250:root): user01

331 Please specify the password.

Password: (user01 사용자 암호 입력)

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> dir

200 PORT command successful. Consider using PASV.

150 Here comes the directory listing.

-rw-r--r-- 1 501 501 5242880 Oct 10 02:27 test.txt

226 Directory send OK.

ftp> mget test.txt

mget test.txt? y

200 PORT command successful. Consider using PASV.

150 Opening BINARY mode data connection for test.txt (5242880 bytes).

226 Transfer complete.

5242880 bytes received in 0.06 secs (80610.9 kB/s)

ftp> quit

221 Goodbye.

 

 

 

$ ftp 192.168.20.203

Connected to 192.168.10.250.

220 (vsFTPd 2.2.2)

Name (192.168.10.250:root): anonymous

331 Please specify the password.

Password: (id@naver.com)

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> cd pub

250 Directory successfully changed.

ftp> dir

200 PORT command successful. Consider using PASV.

150 Here comes the directory listing.

-rw-r--r-- 1 0 0 1571 Oct 10 02:39 test.txt

226 Directory send OK.

ftp> mget test.txt

mget test.txt? y

200 PORT command successful. Consider using PASV.

150 Opening BINARY mode data connection for test.txt (1571 bytes).

226 Transfer complete.

1571 bytes received in 0.00 secs (1543.4 kB/s)

ftp> quit

221 Goodbye.

 

 

 

 

 

 

(정리) 리눅스 서버에서

만약 SELinux 기능을 enforcing 방식으로 설정할려고 한다면

# vi /etc/sysconfig/selinux

SELINUX=enforcing

SELINUXTYPE=targeted

# setenforce 1

 

새로운 서비스(EX: FTP)Open 하는 경우의 "서비스 Open 설정 절차"

() 프로그램 설치(EX: ?)

# yum -y install ftp vsftpd

() 프로그램 설정

# sed -i 's/^root/#root/' /etc/vsftpd/ftpuser

# sed -i 's/^root/#root/' /etc/vsftpd/user_list

() 서비스를 ON(EX: system-config-services)

# chkconfig vsftpd on

# service vsftpd start

() 방화벽에 서비스를 등록(EX: system-config-firewall)

# iptables -A INPUT -m state --state NEW -p tcp --dport 20-21 -j ACCEPT

# service iptables save /* /etc/sysconfig/iptables */

() SELinux 설정 설정(EX: system-config-selinux)

# setsebool allow_ftpd_full_access on

# setsebool -P allow_ftpd_full_access on

 

 

 

 

 

 

[실습] 임시적으로 context type 변경하는 경우 및 복구 실습

 

# cd

# mkdir text && cd text

# touch file1

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

 

# chcon -t samba_share_t file1

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:samba_share_t:s0 file1

 

# restorecon -v file1

restorecon reset /root/text/file1 context unconfined_u:object_r:samba_share_t:s0->unconfined_u:object_r:admin_home_t:s0

 

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

 

 

 

[실습] file에 대한 contexts 설정된 파일 확인

# cd /etc/selinux/targeted/contexts/files

# ls

file_contexts file_contexts.homedirs file_contexts.local media

 

# cat /etc/selinux/targeted/contexts/files/file_contexts | more

/.* system_u:object_r:default_t:s0

/[^/]+ -- system_u:object_r:etc_runtime_t:s0

/a?quota\.(user|group) -- system_u:object_r:quota_db_t:s0

/nsr(/.*)? system_u:object_r:var_t:s0

/sys(/.*)? system_u:object_r:sysfs_t:s0

/xen(/.*)? system_u:object_r:xen_image_t:s0

/mnt(/[^/]*) -l system_u:object_r:mnt_t:s0

/mnt(/[^/]*)? -d system_u:object_r:mnt_t:s0

/bin/.* system_u:object_r:bin_t:s0

/dev/.* system_u:object_r:device_t:s0

/lib/.* system_u:object_r:lib_t:s0

/var/.* system_u:object_r:var_t:s0

/srv/.* system_u:object_r:var_t:s0

/tmp/.* <<none>>

/usr/.* system_u:object_r:usr_t:s0

/opt/.* system_u:object_r:usr_t:s0

/etc/.* system_u:object_r:etc_t:s0

/root(/.*)? system_u:object_r:admin_home_t:s0

/dev/[0-9].* -c system_u:object_r:usb_device_t:s0

/mnt/[^/]*/.* <<none>>

/dev/.*mouse.* -c system_u:object_r:mouse_device_t:s0

/rhev(/[^/]*)? -d system_u:object_r:mnt_t:s0

/dev/.*tty[^/]* -c system_u:object_r:tty_device_t:s0

 

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

 

/usr/share/gitolite3/triggers/post-compile/ssh-authkeys-shell-users -- sys

tem_u:object_r:bin_t:s0

/usr/share/gitolite3/triggers/post-compile/update-gitweb-access-list -- sys

tem_u:object_r:bin_t:s0

/usr/share/system-config-securitylevel/system-config-securitylevel\.py -- sys

tem_u:object_r:bin_t:s0

/usr/share/system-config-services/system-config-services-mechanism\.py -- sys

tem_u:object_r:initrc_exec_t:s0

/usr/share/gitolite3/triggers/post-compile/update-git-daemon-access-list --system_u:object_r:bin_t:s0

-> 나중에 restorecon 명령어 수행시 참고되는 파일이다.

 

 

[실습] 디렉토리 하위의 모든 파일에 대한 context type을 변경 또는 복구

# mkdir /web

# touch /web/file{1,2,3}

# ls -Z /web

-rw-r--r--. root root unconfined_u:object_r:default_t:s0 file1

-rw-r--r--. root root unconfined_u:object_r:default_t:s0 file2

-rw-r--r--. root root unconfined_u:object_r:default_t:s0 file3

 

# chcon -R -t httpd_sys_content_t /web

# ls -dZ /web

drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 /web

 

# ls -lZ /web

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file3

 

# restorecon -R -v /web

restorecon reset /web context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:default_t:s0

restorecon reset /web/file2 context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:default_t:s0

restorecon reset /web/file3 context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:default_t:s0

restorecon reset /web/file1 context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:default_t:s0

 

 

 

[실습] context type 영구적으로 변경하기

 

(임시적으로 변경) chcon CMD 사용

(영구적으로 변경) semanage fcontext CMD 사용

 

# touch /etc/file1

# ls -Z /etc/file1

-rw-r--r--. root root unconfined_u:object_r:etc_t:s0 /etc/file1

 

# semanage fcontext -a -t samba_share_t /etc/file1

#

-> 약간 시간이 걸림(5 ~ 8)

 

# semanage --help

-a, --add Add a OBJECT record NAME

-t, --type SELinux Type for the object

-d, --delete Delete a OBJECT record NAME

 

# ls -Z /etc/file1

-rw-r--r--. root root unconfined_u:object_r:etc_t:s0 /etc/file1

-> 현재 설정이 바뀌었는가?

 

# cat /etc/selinux/targeted/contexts/files/file_contexts.local

# This file is auto-generated by libsemanage

# Do not edit directly.

 

/etc/file1 system_u:object_r:samba_share_t:s0

-> 이 내용은 재부팅이 되어도 지속적으로 동작한다.

 

# semanage fcontext -d /etc/file1

#

-> 약간 시간이 걸림

 

 

 

# cat /etc/selinux/targeted/contexts/files/file_contexts.local

# This file is auto-generated by libsemanage

# Do not edit directly.

 

 

 

 

 

[실습] 파일 복사(Copy)/이동(Move)/삭제(Delete)

 

(필요하면 명령어 수행)

# cat /etc/resolv.conf

# yum -y install httpd httpd-tools httpd-manual

 

# su - user01

$ touch file1

$ ls -Z file1

-rw-rw-r--. user01 user01 unconfined_u:object_r:user_home_t:s0 file1

-rw-r--r--. user01 user01 unconfined_u:object_r:user_home_t:s0 test.txt

 

$ ls -dZ /var/www/html

drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /var/www/html

 

$ exit

 

# cd /home/user01

# ls -Z file1

-rw-rw-r--. user01 user01 unconfined_u:object_r:user_home_t:s0 file1

 

# cp file1 /var/www/html

# ls -Z /var/www/html

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1

 

# cd /root/text

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

 

# cp --preserve=context file1 /var/www

# ls -Z /var/www

drwxr-xr-x. root root system_u:object_r:httpd_sys_script_exec_t:s0 cgi-bin

drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 error

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 html

drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 icons

drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 manual

 

# su - user01

$ ls -Z

-rw-rw-r--. user01 user01 unconfined_u:object_r:user_home_t:s0 file1

 

$ cp -Z system_u:object_r:samba_share_t:s0 file1 file2

$ ls -Z

-rw-rw-r--. user01 user01 unconfined_u:object_r:user_home_t:s0 file1

-rw-rw-r--. user01 user01 system_u:object_r:samba_share_t:s0 file2

 

$ exit

 

# ls -Z

-rw-rw-r--. user01 user01 unconfined_u:object_r:user_home_t:s0 file1

-rw-rw-r--. user01 user01 system_u:object_r:samba_share_t:s0 file2

-rw-r--r--. user01 user01 unconfined_u:object_r:user_home_t:s0 test.txt

# cp -Z system_u:object_r:samba_share_t:s0 file1 file2

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

-rw-r--r--. root root system_u:object_r:samba_share_t:s0 file2

 

# ls -Z /var/www/html

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1

 

# rm -rf /var/www/html/file1

#

 

# pwd

/root/text

 

# ls -Z

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

-rw-r--r--. root root system_u:object_r:samba_share_t:s0 file2

 

# mv file1 /var/www/html

# ls -Z /var/www/html/file1

-rw-r--r--. root root unconfined_u:object_r:admin_home_t:s0 file1

 

# cd /var/www/html

# rm -rf file1

 

# touch file{1,2,3}

# ls -Z file*

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file3

 

# chcon -t samba_share_t file1

# ls -Z file*

-rw-r--r--. root root unconfined_u:object_r:samba_share_t:s0 file1

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file3

 

# matchpathcon -V /var/www/html/file* file1 (# matchpathcon -V /var/www/html/*)

/var/www/html/file1 has context unconfined_u:object_r:samba_share_t:s0, should be system_u:object_r:httpd_sys_content_t:s0

/var/www/html/file2 verified.

/var/www/html/file3 verified.

 

# restorecon -v file1

restorecon reset /var/www/html/file1 context unconfined_u:object_r:samba_share_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0

 

# ls -Z file*

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file1

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file2

-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 file3

 

 

 

 

 

(정리) 예제 : 웹서비스(httpd, /etc/httpd/conf/httpd.conf, 80)

데몬 이름 : /usr/sbin/httpd

주 설정 파일 : /etc/httpd/conf/httpd.conf

서비스 포트 : 80

웹 디렉토리 : /var/www/html

 

 

 

새로운 서비스(EX: FTP)Open 하는 경우의 "서비스 Open 설정 절차"

() 소프트웨어 설치

# yum -y install httpd httpd-tools

 

() 서비스를 ON

# chkconfig httpd on

# service httpd start

 

() 방화벽에 서비스를 등록

# iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT

# service iptables save /* /etc/sysconfig/iptables */

 

() SELinux 설정 설정

(서비스 boolean 설정)

# getsebool -a | grep httpd

-> audit messages (AVC denied 메세지를 확인)

-> 적당한 기능 on

(EX) # setsebool httpd_enable_homedirs on

# setsebool -P httpd_enable_homedires on

 

(서비스 데몬이 읽어 들이는 파일)

-> audit messages (AVC denied 메세지를 확인)

(EX) # mv /home/user01/index.html /var/www/html

# chcon -t httpd_sys_content_t /var/www/html/index.html

# semanage fcontext -a -t httpd_sys_content_t /var/www/html/index.html

 

 

 

 


u: user

r: role

t: type

s: security level






'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160804 Linux and Unix sudo command  (0) 2016.08.04
20160804 SELinux  (0) 2016.08.04
20160803 소프트웨어 관리  (0) 2016.08.03
20160802 웹 방화벽  (0) 2016.08.02
20160802 Snort  (0) 2016.08.02
Posted by 22Hz
, |

4

Create an RPM

 

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

간단한 프로그램 개발

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# mkdir -p /test/hello-1.0

# cd /test

# vi hello-1.0/hello.sh

#!/bin/bash

 

echo 'This is a test.'

echo

 

echo ' ________________________'

echo '/ \'

echo '| |'

echo '| !! 공부좀 해라!!! |'

echo '| |'

echo '\________________________/'

echo ' \'

echo ' \'

echo ' (__)'

echo ' (oo)______'

echo ' (__) )\'

echo ' ||---|| *'

echo ' || ||'

echo

 

 

tar.gz 파일 생성

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

(필요하면 명령어 수행)

# ls /usr/src/redhat

ls: /usr/src/redhat: No such file or directory

# yum -y install rpm-build

 

# ls /usr/src/redhat

BUILD/ RPMS/ SOURCES/ SPECS/ SRPMS/

 

# tar cvzf /usr/src/redhat/SOURCES/hello-1.0-1.tar.gz hello-1.0

# tar tvzf /usr/src/redhat/SOURCES/hello-1.0-1.tar.gz

drwxr-xr-x root/root 0 2014-01-23 16:16:24 hello-1.0/

-rwxr-xr-x root/root 394 2014-01-23 16:16:24 hello-1.0/hello.sh

 

SPEC 파일 생성

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# vi /usr/src/redhat/SPECS/hello.spec

%define name hello

%define version 1.0

%define release 1

 

Name: hello

Version: 1.0

Release: 1

Summary: Hello

Group: CentOS

License: GPL

URL: http://www.example.com

Source0: %{name}-%{version}-%{release}.tar.gz

BuildRoot: /var/tmp/%{name}-buildroot

 

%description

Installs /root/bin/hello.sh

 

%prep

%setup -q -n %{name}-%{version}

 

%build

 

%install

rm -rf $RPM_BUILD_ROOT

mkdir -p $RPM_BUILD_ROOT/root/bin

install -m 755 hello.sh $RPM_BUILD_ROOT/root/bin/hello.sh

 

%clean

rm -rf $RPM_BUILD_ROOT

 

%files

%defattr(-,root,root,-)

/root/bin/hello.sh

 

%changelog

 

rpm build

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# yum -y install rpm-build

-> rpm-build 패키지 설치

 

# rpmbuild -ba /usr/src/redhat/SPECS/hello.spec

Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.38857

+ umask 022

+ cd /usr/src/redhat/BUILD

+ cd /usr/src/redhat/BUILD

+ rm -rf hello-1.0

+ /bin/gzip -dc /usr/src/redhat/SOURCES/hello-1.0-1.tar.gz

+ tar -xf -

+ STATUS=0

+ '[' 0 -ne 0 ']'

+ cd hello-1.0

++ /usr/bin/id -u

+ '[' 0 = 0 ']'

+ /bin/chown -Rhf root .

++ /usr/bin/id -u

+ '[' 0 = 0 ']'

+ /bin/chgrp -Rhf root .

+ /bin/chmod -Rf a+rX,u+w,g-w,o-w .

+ exit 0

Executing(%build): /bin/sh -e /var/tmp/rpm-tmp.38857

+ umask 022

+ cd /usr/src/redhat/BUILD

+ cd hello-1.0

+ exit 0

Executing(%install): /bin/sh -e /var/tmp/rpm-tmp.38857

+ umask 022

+ cd /usr/src/redhat/BUILD

+ cd hello-1.0

+ rm -rf /var/tmp/hello-buildroot

+ mkdir -p /var/tmp/hello-buildroot/root/bin

+ install -m 755 hello.sh /var/tmp/hello-buildroot/root/bin/hello.sh

+ /usr/lib/rpm/brp-compress

+ /usr/lib/rpm/brp-strip

+ /usr/lib/rpm/brp-strip-static-archive

+ /usr/lib/rpm/brp-strip-comment-note

Processing files: hello-1.0-1

Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1

Requires: /bin/bash

Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/tmp/hello-buildroot

Wrote: /usr/src/redhat/SRPMS/hello-1.0-1.src.rpm

Wrote: /usr/src/redhat/RPMS/i386/hello-1.0-1.i386.rpm

Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.38857

+ umask 022

+ cd /usr/src/redhat/BUILD

+ cd hello-1.0

+ rm -rf /var/tmp/hello-buildroot

+ exit 0

 

# find /usr/src/redhat

/usr/src/redhat

/usr/src/redhat/RPMS

/usr/src/redhat/RPMS/geode

/usr/src/redhat/RPMS/noarch

/usr/src/redhat/RPMS/i386

/usr/src/redhat/RPMS/i386/hello-1.0-1.i386.rpm

/usr/src/redhat/RPMS/i686

/usr/src/redhat/RPMS/athlon

/usr/src/redhat/RPMS/i486

/usr/src/redhat/RPMS/i586

/usr/src/redhat/SOURCES

/usr/src/redhat/SOURCES/hello-1.0-1.tar.gz

/usr/src/redhat/SPECS

/usr/src/redhat/SPECS/hello.spec

/usr/src/redhat/SRPMS

/usr/src/redhat/SRPMS/hello-1.0-1.src.rpm

/usr/src/redhat/BUILD

/usr/src/redhat/BUILD/hello-1.0

/usr/src/redhat/BUILD/hello-1.0/hello.sh

 

생성된 패키지 설치 및 삭제(테스트용)

# cd /usr/src/redhat/RPMS/i386

# rpm -Uvh hello-1.0-1.i386.rpm

Preparing... ########################################### [100%]

1:hello ########################################### [100%]

 

# rpm -e hello

# rpm -qa | grep hello

#

 

 

 

 

GPG Key 생성과 패키지 sign

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# cd

# gpg --gen-key

gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.

This program comes with ABSOLUTELY NO WARRANTY.

This is free software, and you are welcome to redistribute it

under certain conditions. See the file COPYING for details.

 

gpg: directory `/root/.gnupg' created

gpg: new configuration file `/root/.gnupg/gpg.conf' created

gpg: WARNING: options in `/root/.gnupg/gpg.conf' are not yet active during this run

gpg: keyring `/root/.gnupg/secring.gpg' created

gpg: keyring `/root/.gnupg/pubring.gpg' created

Please select what kind of key you want:

(1) DSA and Elgamal (default)

(2) DSA (sign only)

(5) RSA (sign only)

Your selection? <ENTER>

DSA keypair will have 1024 bits.

ELG-E keys may be between 1024 and 4096 bits long.

What keysize do you want? (2048) <ENTER>

Please specify how long the key should be valid.

0 = key does not expire

<n> = key expires in n days

<n>w = key expires in n weeks

<n>m = key expires in n months

<n>y = key expires in n years

Key is valid for? (0) <ENTER>

Key does not expire at all

Is this correct? (y/N) y

 

You need a user ID to identify your key; the software constructs the user ID

from the Real Name, Comment and Email Address in this form:

"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

 

Real name: Baik, SeoungChan

Email address: jang4sc@hanmail.net

Comment: <ENTER>

You selected this USER-ID:

"Baik, SeoungChan <jang4sc@hanmail.net>"

 

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o

You need a Passphrase to protect your secret key.

 

Passphrase: testing123

Repeat passphrase: testing123

We need to generate a lot of random bytes. It is a good idea to perform

some other action (type on the keyboard, move the mouse, utilize the

disks) during the prime generation; this gives the random number

generator a better chance to gain enough entropy.

++++++++++..++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++.+++++++++++++++.+++++.+++++..++++++++++..>+++++.....................................................+++++

 

Not enough random bytes available. Please do some other work to give

the OS a chance to collect more entropy! (Need 283 more bytes)

We need to generate a lot of random bytes. It is a good idea to perform

some other action (type on the keyboard, move the mouse, utilize the

disks) during the prime generation; this gives the random number

generator a better chance to gain enough entropy.

.+++++++++++++++++++++++++.++++++++++.+++++.++++++++++......+++++++++++++++..+++++++++++++++..+++++.+++++++++++++++.+++++++++++++++++++++++++.+++++.++++++++++.+++++>.+++++.+++++...>+++++..................................................................................+++++^^^

gpg: /root/.gnupg/trustdb.gpg: trustdb created

gpg: key ACD89B3E marked as ultimately trusted

public and secret key created and signed.

 

gpg: checking the trustdb

gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model

gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u

pub 1024D/ACD89B3E 2014-01-23

Key fingerprint = 98A1 E2A6 AE47 FE97 BFE8 6DC4 BCAB 0ADE ACD8 9B3E

uid Baik, SeoungChan <jang4sc@hanmail.net>

sub 2048g/CA2DE316 2014-01-23

-> Key ID 확인: ACD89B3E

 

~/RPM-GPG-KEY-test 파일 생성

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# gpg -a -o ~/RPM-GPG-KEY-test --export ACD89B3E

# ls RPM*

RPM-GPG-KEY-test

 

# cat RPM-GPG-KEY-test

-----BEGIN PGP PUBLIC KEY BLOCK-----

Version: GnuPG v1.4.5 (GNU/Linux)

 

mQGiBFLgyxARBACCnrOlR6uregf1SuoqqHxtBXGVq5QKyJVBsb4cXufe0ur5jzk8

Bmc9aKFMnfrp22GZ+CjfBr0BBYCB2A7ANsKtdwNzB2PHl7C9BNQafS8xrpyTo/2C

oc0j21uLJz5TOpcaQ/1qS/jpUNumvDuoD9RXO6fgPhBNaj808cncp6uQ8wCg3gxc

J4bqvc+QjdTXbrcIuMwDIT0D/A++D26YIp0TpzVDmv7Di2GTc4mn6fpKKSLu7vVZ

3IDJuN2B9CL0DJz02S+IR5kF+yf5o6NnUcM9b65nw15MK2d37NE6mOpoUUHao80f

ShAvtQLJl5bVcJWeCz9ORfQqWb36SWLxAJq7TPDsS6l1DUkE3kONQgSZnAzpP4KK

ZS1EA/0aSpKk+/pElSG5muip2xMcflk6ihuGgivcxYlr/E/v2wsH5QELtNt7q4wj

K2ji/QuZabdEi5V77qUHbUvLo2d4By0mB6EPAV6Nk3V9iV7SdKYKb7f01ybuW82s

bzMnfaK2bOmN/7A9LCKk5eQ5urN9Jr8q159kOHaCroTQrelC77QmQmFpaywgU2Vv

dW5nQ2hhbiA8amFuZzRzY0BoYW5tYWlsLm5ldD6IYAQTEQIAIAUCUuDLEAIbAwYL

CQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJELyrCt6s2Js+kwcAn3K/hdtIVFLpWwyX

/65RsA/hWf/tAJ9oA1Sp3M/QSrGwPEwiadjDFr2io7kCDQRS4MsUEAgA5XtEwdw7

H3+yxxObgv+giZWd2oNxjfmrWqecd2N6+dsgR3oc1kbYdv84jU6icozZxz7XHbAR

1Hxj+f31H56k6W8ZXVx0W0qMZSCOcuXY+dmQJV9qcJfzdDc1HahTUL32C6Vz0Emh

L7A2HSgj8apoSkER9YBY9jUAseE9FK7YalhPfIUW79CcY9zSUvmGBiXvpume7+M9

xtwDcaxAA9J46KWDUpuzkCl6n/ru5LbqSv2/qNBIep+eut8WWmEnP5MzFigK0gjs

cP5EnUceNFTmKnw9hwG3pzprJPmd1iu/VbLa3XySmQlrSyWjziZcdquUqq0KxJdC

c7QhQ/kYHS3g9wADBQf/X6il933Tu4s7qKqxz+pIkAcIAkCTvBfePUWqmZ9Rw+S/

amWayHU18rXfJ0+Wo3PK6Hs4FjO/tZamTJokfrleIk9weOLOp6wZVMA0TTcrTpi6

FTp36vWUVveysjuHQa43RpfPqgJNQdgSFUVfm4wMxBFVDS8itx5RWxqmvrPJLrur

egm1EiXNDK+b8Tv1vxHcgiPfcls8Y6gtWvPM7lbH5KY4ORj9oaHB+DhFRPgR6U9l

gFGVQuI6UP4G+3MSNoMEJIuVq0R1r9unytL+ojdyfLisgC2Xja3Z6lZZ67I0RiLr

ZpFuAcROxgtcNsCHmle0DI3Bv9pBCJ8nudeSHahQsohJBBgRAgAJBQJS4MsUAhsM

AAoJELyrCt6s2Js+oLoAoLVRgzLFoBmYiZXKIexIHhbrlRRIAKCaOHPRd4+88L1J

WVbsdJED3F7cAQ==

=lq3h

-----END PGP PUBLIC KEY BLOCK-----

 

~/.rpmmacros 파일 생성

# vi ~/.rpmmacros

%_gpg_name ACD89B3E

 

패키지 sign

 

# rpm --resign /usr/src/redhat/RPMS/i386/hello-1.0-1.i386.rpm

Enter pass phrase: testing123

Pass phrase is good.

/usr/src/redhat/RPMS/i386/hello-1.0-1.i386.rpm:

gpg: WARNING: standard input reopened

gpg: WARNING: standard input reopened

 

 

 

 

배포 서버 구성(YUM Repository)

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# mkdir /var/www/html/packages

# cp /usr/src/redhat/RPMS/i386/hello*.rpm /var/www/html/packages

# cp RPM-GPG-KEY-test /var/www/html/packages

 

# yum -y install createrepo

# createrepo /var/www/html/packages

1/1 - hello-1.0-1.i386.rpm

 

Saving Primary metadata

Saving file lists metadata

Saving other metadata

 

# service httpd start

 

hello.repo 파일 생성

 

rpm 패키지 생성 절차

() 소스 프로그램 개발

() 소스.tar.gz 파일 생성

() SPEC 파일 생성

() rpm build

() GPG Key 생성

() 패키지 sign

() Yum Repository 구성

() 테스트

 

# vi /etc/yum.repos.d/hello.repo

[hello]

name=hello

description=Test Yum Repository

baseurl=http://172.16.9.252/packages

enabled=1

gpgcheck=1

gpgkey=http://172.16.9.252/packages/RPM-GPG-KEY-test

 

설치 확인

# yum -y install hello

Loaded plugins: fastestmirror, security

Loading mirror speeds from cached hostfile

* base: mirror.oasis.onnetcorp.com

* extras: mirror.oasis.onnetcorp.com

* updates: mirror.oasis.onnetcorp.com

hello | 951 B 00:00

hello/primary | 668 B 00:00

hello 1/1

Setting up Install Process

Resolving Dependencies

--> Running transaction check

---> Package hello.i386 0:1.0-1 set to be updated

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Installing:

hello i386 1.0-1 hello 2.2 k

 

Transaction Summary

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

Install 1 Package(s)

Upgrade 0 Package(s)

 

Total download size: 2.2 k

Downloading Packages:

hello-1.0-1.i386.rpm | 2.2 kB 00:00

warning: rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID c1d1124a

hello/gpgkey | 1.6 kB 00:00

Importing GPG key 0xC1D1124A "baik,seoungchan <jang4sc@hanmail.net>" from http://172.16.10.249/packages/RPM-GPG-KEY-test

Running rpm_check_debug

Running Transaction Test

Finished Transaction Test

Transaction Test Succeeded

Running Transaction

Installing : hello 1/1

 

Installed:

hello.i386 0:1.0-1

 

Complete!

 

# hello.sh

This is a test.

 

________________________

/ \

| |

| !! 공부좀 해라!!! |

| |

\________________________/

\

\

(__)

(oo)______

(__) )\

||---|| *

|| ||

 

 

 

 

 

(복원) hello.repo 파일 복원

# cd /etc/yum.repos.d

# vi hello.repo

[hello]

name=hello

description=Test Yum Repository

baseurl=http://172.16.9.252/packages

enabled=0

gpgcheck=1

gpgkey=http://172.16.9.252/packages/RPM-GPG-KEY-test

 

 

 

 

 

 

 


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160804 SELinux  (0) 2016.08.04
20160803 SELinux  (0) 2016.08.03
20160802 웹 방화벽  (0) 2016.08.02
20160802 Snort  (0) 2016.08.02
20160801 IDS  (0) 2016.08.01
Posted by 22Hz
, |

 

 

 

웹 방화벽(WAF, Web Application Firewall)

 

 

 

 

 

(1) 웹방화벽이란? (Application Proxy 역할)

 

웹클라이언트 -------> 방화벽 -----> IPS(침입차단시스템) ----> WAF(웹방화벽) ---> 웹서버

(웹브라우저) (iptables) (snort + prevent) (modsecurity) (linux200)

 

 

 


 

 

 

(2) 무료 웹 방화벽

 

최근 홈페이지를 통한 악성코드 유포, 피싱 사이트로 악용 등 웹 해킹의 피해가 심각한 수준에 이르고 있다. 한국정보보호진흥원은 신규 보안투자 여력이 없는 중소기업의 웹 보안 강화를 위해 기본적인 웹 해킹을 차단할 수 있는 공개웹방화벽 2종을 추천하고 있다.

 

 

WebKnight

 

AQTRONIX 사에서 개발한 IIS 웹서버용 공개 웹방화벽으로 SQL Injection 공격 등 IIS 웹서버의 주용 공격 차단 기능을 가지고 있다.

홈페이지: http://www.aqtronic.com/?PageID=99

 

 

 

ModSecurity

 

Ivan Ristic이 개발한 Apache 웹서버용 공개 웹방화벽으로 PHP Injection 공격등 Apache 웹서버의 주요 공격을 차단하는 기능을 가지고 있다.

홈페이지: http://www.modsecurity.org

 

 

 

자세한 사항은 다음을 참고한다.

공개용 웹방화벽

http://www.krcert.or.kr/download/webFirewall.do

 

() http://www.krcert.or.kr > 상단의 '다운로드' > '공개 웹 방화벽'

() 자료실 > "modsecurity" 검색 > 관련 파일 다운로드

 

웹 취약점 점검

http://www.krcert.or.kr/webprotect/webVulnerability.do

 

() http://www.krcert.or.kr > 상단의 '다운로드' > '웹 취약점 점검'

 

 

 

 

 

(3) 웹방화벽 구축 사례

 


 

 


 

 


 

 


 

 

 

 

 

(4) 웹 취약점 무료 점검 서비스

 

http://www.krcert.or.kr/webprotect/webVulnerability.do

 


 

 

 

(5) 실습은 인터넷을 통해 검색하여 문서를 작성한다.(시간: 30분 정도)

-> http://www.youtube.com

검색 키워드: "modsecurity"

검색 키워드: "modsecurity tutorial"

검색 키워드: "modsecurity centos"

검색 키워드: "modsecurity configuration"

검색 키워드: "modsecurity setup"

 

 

 

 

 

[실습] WAF 설치 및 테스트

 

사용시스템

linux200 (WAF + WEB Server)

KaliLinux(Attacker)

 

 

(linux200) 192.168.20.200

 

---- linux200 --- ---- linux200 ----

 

---> WAF(Web Application Firewall) <----> Apache Web Server

modsecurity

 

 

modsecurity 다운로드

http://www.modsecurity.org

-> 오른쪽 상단의 "Get Code" 하단에 "Source/Binary" 선택

 


 

Community Repository 구성

http://www.modsecurity.org/download.html

-> 오른쪽 상단의 "Commnuity Repostory" 부분에서 "RHEL/CentOS Yum Repository (Jason Litka)" 선택

 


Yum Repository <--------- # yum -y install <PKG>

/etc/yum.repos.d/*.repo

 

# cd /etc/pki/rpm-gpg

# rpm --import http://yum.jasonlitka.com/RPM-GPG-KEY-jlitka

#

 

# vi /etc/yum.repos.d/utterramblings.repo

[utterramblings]

name=Jason's Utter Ramblings Repo

baseurl=http://yum.jasonlitka.com/EL$releasever/$basearch/

enabled=1

gpgcheck=1

gpgkey=http://yum.jasonlitka.com/RPM-GPG-KEY-jlitka

 

[참고] 파일에 대한 해석

[utterramblings]

name=Jason's Utter Ramblings Repo

baseurl=http://yum.jasonlitka.com/EL$releasever/$basearch/

enabled=1 /* enable : 1, disable : 0 */

gpgcheck=1 /* check : 1, uncheck : 0 */

gpgkey=http://yum.jasonlitka.com/RPM-GPG-KEY-jlitka

 

 

mod_security/httpd/httpd-devel 패키지 설치

 

(주의) 반드시 스냅샷을 생성한다.

(주의) 웹 데몬 종료 (# service httpd stop; # chkconfig httpd off)

 

# yum -y install mod_security

-> 약간 시간이 걸린다.

 

(32 bits OS) # yum -y install httpd httpd-devel

(64 bits OS) # yum -y install httpd.x86_64 httpd-devel.x86_64 httpd-manual.x86_64

Loaded plugins: fastestmirror, security

Loading mirror speeds from cached hostfile

* base: mirror.premi.st

* extras: mirror.premi.st

* rpmforge: ftp.riken.jp

* updates: data.nicehosting.co.kr

Setting up Install Process

Resolving Dependencies

--> Running transaction check

--> Processing Dependency: httpd = 2.2.3-87.el5.centos for package: httpd-manual

--> Processing Dependency: httpd = 2.2.3-87.el5.centos for package: mod_ssl

---> Package httpd.i386 0:2.2.22-jason.1 set to be updated

--> Processing Dependency: apr-util-ldap for package: httpd

---> Package httpd-devel.i386 0:2.2.22-jason.1 set to be updated

--> Processing Dependency: apr-util-devel for package: httpd-devel

--> Processing Dependency: apr-devel for package: httpd-devel

--> Running transaction check

---> Package apr-devel.i386 0:1.4.5-1.jason.1 set to be updated

--> Processing Dependency: apr = 1.4.5-1.jason.1 for package: apr-devel

---> Package apr-util-devel.i386 0:1.3.12-1.jason.1 set to be updated

--> Processing Dependency: apr-util = 1.3.12-1.jason.1 for package: apr-util-devel

--> Processing Dependency: openldap-devel for package: apr-util-devel

--> Processing Dependency: expat-devel for package: apr-util-devel

--> Processing Dependency: db4-devel for package: apr-util-devel

---> Package apr-util-ldap.i386 0:1.3.12-1.jason.1 set to be updated

---> Package httpd-manual.i386 0:2.2.22-jason.1 set to be updated

---> Package mod_ssl.i386 1:2.2.22-jason.1 set to be updated

--> Running transaction check

---> Package apr.i386 0:1.4.5-1.jason.1 set to be updated

---> Package apr-util.i386 0:1.3.12-1.jason.1 set to be updated

---> Package db4-devel.i386 0:4.3.29-10.el5_5.2 set to be updated

---> Package expat-devel.i386 0:1.95.8-11.el5_8 set to be updated

---> Package openldap-devel.i386 0:2.3.43-28.el5_10 set to be updated

--> Processing Dependency: cyrus-sasl-devel >= 2.1 for package: openldap-devel

--> Running transaction check

---> Package cyrus-sasl-devel.i386 0:2.1.22-7.el5_8.1 set to be updated

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Installing:

httpd-devel i386 2.2.22-jason.1 utterramblings 151 k

Updating:

httpd i386 2.2.22-jason.1 utterramblings 3.0 M

Installing for dependencies:

apr-devel i386 1.4.5-1.jason.1 utterramblings 181 k

apr-util-devel i386 1.3.12-1.jason.1 utterramblings 70 k

apr-util-ldap i386 1.3.12-1.jason.1 utterramblings 19 k

cyrus-sasl-devel i386 2.1.22-7.el5_8.1 base 1.4 M

db4-devel i386 4.3.29-10.el5_5.2 base 1.9 M

expat-devel i386 1.95.8-11.el5_8 base 132 k

openldap-devel i386 2.3.43-28.el5_10 updates 2.9 M

Updating for dependencies:

apr i386 1.4.5-1.jason.1 utterramblings 258 k

apr-util i386 1.3.12-1.jason.1 utterramblings 196 k

httpd-manual i386 2.2.22-jason.1 utterramblings 989 k

mod_ssl i386 1:2.2.22-jason.1 utterramblings 324 k

 

Transaction Summary

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

Install 8 Package(s)

Upgrade 5 Package(s)

 

Total download size: 11 M

Downloading Packages:

(1/13): apr-util-ldap-1.3.12-1.jason.1.i386.rpm | 19 kB 00:00

(2/13): apr-util-devel-1.3.12-1.jason.1.i386.rpm | 70 kB 00:01

(3/13): expat-devel-1.95.8-11.el5_8.i386.rpm | 132 kB 00:00

(4/13): httpd-devel-2.2.22-jason.1.i386.rpm | 151 kB 00:01

(5/13): apr-devel-1.4.5-1.jason.1.i386.rpm | 181 kB 00:02

(6/13): apr-util-1.3.12-1.jason.1.i386.rpm | 196 kB 00:01

(7/13): apr-1.4.5-1.jason.1.i386.rpm | 258 kB 00:02

(8/13): mod_ssl-2.2.22-jason.1.i386.rpm | 324 kB 00:04

(9/13): httpd-manual-2.2.22-jason.1.i386.rpm | 989 kB 00:11

(10/13): cyrus-sasl-devel-2.1.22-7.el5_8.1.i386.rpm | 1.4 MB 00:00

(11/13): db4-devel-4.3.29-10.el5_5.2.i386.rpm | 1.9 MB 00:00

(12/13): openldap-devel-2.3.43-28.el5_10.i386.rpm | 2.9 MB 00:01

(13/13): httpd-2.2.22-jason.1.i386.rpm | 3.0 MB 00:39

-----------------------------------------------------------------------------------------------------------------------------

Total 172 kB/s | 11 MB 01:08

Running rpm_check_debug

Running Transaction Test

Finished Transaction Test

Transaction Test Succeeded

Running Transaction

Updating : apr 1/18

Updating : apr-util 2/18

Installing : apr-util-ldap 3/18

Updating : httpd 4/18

warning: /etc/httpd/conf/httpd.conf created as /etc/httpd/conf/httpd.conf.rpmnew

Installing : cyrus-sasl-devel 5/18

Installing : apr-devel 6/18

Installing : openldap-devel 7/18

Installing : db4-devel 8/18

Installing : expat-devel 9/18

Installing : apr-util-devel 10/18

Updating : mod_ssl 11/18

Installing : httpd-devel 12/18

Updating : httpd-manual 13/18

Cleanup : mod_ssl 14/18

Cleanup : httpd 15/18

Cleanup : apr-util 16/18

Cleanup : httpd-manual 17/18

Cleanup : apr 18/18

 

Installed:

httpd-devel.i386 0:2.2.22-jason.1

 

Dependency Installed:

apr-devel.i386 0:1.4.5-1.jason.1 apr-util-devel.i386 0:1.3.12-1.jason.1 apr-util-ldap.i386 0:1.3.12-1.jason.1

cyrus-sasl-devel.i386 0:2.1.22-7.el5_8.1 db4-devel.i386 0:4.3.29-10.el5_5.2 expat-devel.i386 0:1.95.8-11.el5_8

openldap-devel.i386 0:2.3.43-28.el5_10

 

Updated:

httpd.i386 0:2.2.22-jason.1

 

Dependency Updated:

apr.i386 0:1.4.5-1.jason.1 apr-util.i386 0:1.3.12-1.jason.1 httpd-manual.i386 0:2.2.22-jason.1

mod_ssl.i386 1:2.2.22-jason.1

 

Complete!

 

 

 

# yum -y install pcre pcre-devel

Loaded plugins: fastestmirror, security

Loading mirror speeds from cached hostfile

* base: mirror.premi.st

* extras: mirror.premi.st

* rpmforge: ftp.riken.jp

* updates: data.nicehosting.co.kr

Setting up Install Process

Resolving Dependencies

--> Running transaction check

---> Package pcre.i386 0:8.13-1.jason.2 set to be updated

---> Package pcre-devel.i386 0:8.13-1.jason.2 set to be updated

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Updating:

pcre i386 8.13-1.jason.2 utterramblings 509 k

pcre-devel i386 8.13-1.jason.2 utterramblings 438 k

 

Transaction Summary

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

Install 0 Package(s)

Upgrade 2 Package(s)

 

Total download size: 946 k

Downloading Packages:

(1/2): pcre-devel-8.13-1.jason.2.i386.rpm | 438 kB 00:02

(2/2): pcre-8.13-1.jason.2.i386.rpm | 509 kB 00:01

-----------------------------------------------------------------------------------

Total 202 kB/s | 946 kB 00:04

Running rpm_check_debug

Running Transaction Test

Finished Transaction Test

Transaction Test Succeeded

Running Transaction

Updating : pcre 1/4

Updating : pcre-devel 2/4

Cleanup : pcre 3/4

Cleanup : pcre-devel 4/4

 

Updated:

pcre.i386 0:8.13-1.jason.2 pcre-devel.i386 0:8.13-1.jason.2

 

Complete!

 

 

 

mod_security 패키지 설치 확인

# rpm -qa | grep mod_security

mod_security-2.5.9-1.jason.1

 

# rpm -ql mod_security

/etc/httpd/conf.d/mod_security.conf

/etc/httpd/modsecurity.d

/etc/httpd/modsecurity.d/modsecurity_crs_10_config.conf

/etc/httpd/modsecurity.d/modsecurity_crs_20_protocol_violations.conf

/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf

/etc/httpd/modsecurity.d/modsecurity_crs_23_request_limits.conf

/etc/httpd/modsecurity.d/modsecurity_crs_30_http_policy.conf

/etc/httpd/modsecurity.d/modsecurity_crs_35_bad_robots.conf

/etc/httpd/modsecurity.d/modsecurity_crs_40_generic_attacks.conf

/etc/httpd/modsecurity.d/modsecurity_crs_45_trojans.conf

/etc/httpd/modsecurity.d/modsecurity_crs_50_outbound.conf

/etc/httpd/modsecurity.d/modsecurity_localrules.conf

/etc/httpd/modsecurity.d/optional_rules

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_20_protocol_violations.conf

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_21_protocol_anomalies.conf

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_40_generic_attacks.conf

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_42_comment_spam.conf

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_42_tight_security.conf

/etc/httpd/modsecurity.d/optional_rules/modsecurity_crs_55_marketing.conf

/etc/mlogc.conf

/usr/bin/mlogc

/usr/lib/httpd/modules/mod_security2.so

/usr/share/doc/mod_security-2.5.9

/usr/share/doc/mod_security-2.5.9/CHANGES

/usr/share/doc/mod_security-2.5.9/LICENSE

/usr/share/doc/mod_security-2.5.9/MODSECURITY_LICENSING_EXCEPTION

/usr/share/doc/mod_security-2.5.9/README.TXT

/usr/share/doc/mod_security-2.5.9/doc

/usr/share/doc/mod_security-2.5.9/doc/apache_request_cycle-modsecurity.jpg

/usr/share/doc/mod_security-2.5.9/doc/breach-logo-small.gif

/usr/share/doc/mod_security-2.5.9/doc/html-multipage

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/actions.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/apache_request_cycle-modsecurity.jpg

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/ar01s02.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/ar01s10.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/ar01s11.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/ar01s12.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/breach-logo-small.gif

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/configuration-directives.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/index.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/installation.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/introduction.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/modsecurity-reference.css

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/modsecurity.gif

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/operators.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/processing-phases.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/transformation-functions.html

/usr/share/doc/mod_security-2.5.9/doc/html-multipage/variables.html

/usr/share/doc/mod_security-2.5.9/doc/index.html

/usr/share/doc/mod_security-2.5.9/doc/migration-matrix.html

/usr/share/doc/mod_security-2.5.9/doc/migration-matrix.xml

/usr/share/doc/mod_security-2.5.9/doc/modsecurity-reference.css

/usr/share/doc/mod_security-2.5.9/doc/modsecurity.gif

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-apache-reference.html

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-apache-reference.pdf

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-apache-reference.xml

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-data-formats.html

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-data-formats.pdf

/usr/share/doc/mod_security-2.5.9/doc/modsecurity2-data-formats.xml

/usr/share/doc/mod_security-2.5.9/modsecurity.conf-minimal

 

 

 

(rules) 파일 다운로드(OWASP CRS(Core Rules Set))

 

http://www.modsecurity.org/

-> 오른쪽 상단의 "Get Rules" 하단의 "Free/Commercial" 부분을 선택

-> 왼쪽 하단의 "OWASP Project Site" 아이콘 선택

-> 오른쪽 상단의 "Quick Download" 하단의 "Latest CRS (ZIP)" 부분을 선택

 


 


 


 

 

 

[참고] 아파치 설치 디렉토리

아파치 패키지 설치 : /etc/httpd/conf

아파치 소스 설치 : /usr/local/apache2/conf

 

 

 

# cd /etc/httpd/conf

# wget https://github.com/SpiderLabs/owasp-modsecurity-crs/zipball/master -O master.zip

--2014-09-23 09:04:05-- https://github.com/SpiderLabs/owasp-modsecurity-crs/zipball/master

Resolving github.com... 192.30.252.130

Connecting to github.com|192.30.252.130|:443... connected.

HTTP request sent, awaiting response... 302 Found

Location: https://codeload.github.com/SpiderLabs/owasp-modsecurity-crs/legacy.zip/master [following]

--2014-09-23 09:04:06-- https://codeload.github.com/SpiderLabs/owasp-modsecurity-crs/legacy.zip/master

Resolving codeload.github.com... 192.30.252.144

Connecting to codeload.github.com|192.30.252.144|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 343684 (336K) [application/zip]

Saving to: `master.zip'

 

100%[===================================================================================>] 343,684 227K/s in 1.5s

 

2014-09-23 09:04:08 (227 KB/s) - `master.zip' saved [343684/343684]

 

# ls

httpd.conf httpd.conf.rpmnew magic master.zip

 

[참고] 파일의 확장자

A.tar.gz -> # tar xvzf A.tar.gz

A.tar.bz2 -> # tar xvjf A.tar.bz2

A.zip -> # unzip A.zip

A.jar -> # jar xvf A.jar

A.gz -> # gunzip A.gz

A.bz2 -> # bunzip2 A.bz2

A.Z -> # uncompress A.Z

 

# unzip master.zip

-> 출력 내용 생략

 

# ls

httpd.conf httpd.conf.rpmnew magic master.zip SpiderLabs-owasp-modsecurity-crs-ebe8790/

 

# mv SpiderLabs-owasp-modsecurity-crs-ebe8790 crs

# ls

crs/ httpd.conf httpd.conf.rpmnew magic master.zip

 

# cd crs

# ls

activated_rules/ INSTALL optional_rules/

base_rules/ LICENSE README.md

CHANGES lua/ slr_rules/

experimental_rules/ modsecurity_crs_10_setup.conf.example util/

 

 

# cat INSTALL

Core Rule Set Quick Setup

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

 

To activate the rules for your web server installation:

 

1) Copy the modsecurity_crs_10_setup.conf.example file to modsecurity_crs_10_setup.conf

and customize the settings for your local environment.

 

The modsecurity_crs_10_setup.conf file includes management rules and directives

that can control important CRS functions. Pay attention to

the SecRuleEngine setting (On by default) and that the SecDefaultAction

directive is set to "pass". The 49 inbound blocking and 59 outbound blocking

rules files use the "block" action which

inherits this setting. This effectively means that you can toggle the

SecDefaultAction setting to decide if you would like to deny on an

anomaly scoring/correlation match.

 

Update the PARANOID_MODE variable setting if you want to become more

aggressive in your detection. Caution - this will cause more false positives.

 

Update the appropriate anomaly scoring levels that will be propagated

to the inbound/outbound blocking files.

 

Update the TX policy settings for allowed Request Methods, File Extensions, etc...

 

2) Enable the CRS rules files you want to use by creating symlinks under the

"activated_rules" directory location. You will want to create symlinks for the

following:

 

1) The main modsecurity_crs_10_setup.conf file

2) Any rules from the base_rules directory

3) Any remaining rules from the optional_rules, slr_rules or experimental_rules directories

 

$ pwd

/usr/local/apache/conf/crs

$ ls

CHANGELOG app_sensor modsecurity_crs_10_setup.conf slr_rules

LICENSE base_rules modsecurity_crs_10_setup.conf.example util

README experimental_rules modsecurity_crs_15_customrules.conf

activated_rules lua optional_rules

$ sudo ln -s /usr/local/apache/conf/crs/modsecurity_crs_10_setup.conf activated_rules/modsecurity_crs_10_setup.conf

$ for f in `ls base_rules/` ; do sudo ln -s /usr/local/apache/conf/crs/base_rules/$f activated_rules/$f ; done

$ for f in `ls optional_rules/ | grep comment_spam` ; do sudo ln -s /usr/local/apache/conf/crs/optional_rules/$f activated_rules/$f ; done

$ ls -l activated_rules

total 216

lrwxr-xr-x 1 root wheel 52 May 17 14:01 GsbMalware.dat -> /usr/local/apache/conf/crs/base_rules/GsbMalware.dat

lrwxr-xr-x 1 root wheel 68 May 17 14:01 modsecurity_35_bad_robots.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_35_bad_robots.data

lrwxr-xr-x 1 root wheel 66 May 17 14:01 modsecurity_35_scanners.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_35_scanners.data

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_40_generic_attacks.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_40_generic_attacks.data

lrwxr-xr-x 1 root wheel 79 May 17 14:01 modsecurity_41_sql_injection_attacks.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_41_sql_injection_attacks.data

lrwxr-xr-x 1 root wheel 74 May 17 14:14 modsecurity_42_comment_spam.data -> /usr/local/apache/conf/crs/optional_rules/modsecurity_42_comment_spam.data

lrwxr-xr-x 1 root wheel 66 May 17 14:01 modsecurity_50_outbound.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_50_outbound.data

lrwxr-xr-x 1 root wheel 74 May 17 14:01 modsecurity_50_outbound_malware.data -> /usr/local/apache/conf/crs/base_rules/modsecurity_50_outbound_malware.data

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_crs_14_customrules.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_14_customrules.conf

lrwxr-xr-x 1 root wheel 57 May 17 14:22 modsecurity_crs_10_setup.conf -> /usr/local/apache/conf/crs/modsecurity_crs_10_setup.conf

lrwxr-xr-x 1 root wheel 81 May 17 14:01 modsecurity_crs_20_protocol_violations.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_20_protocol_violations.conf

lrwxr-xr-x 1 root wheel 80 May 17 14:01 modsecurity_crs_21_protocol_anomalies.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_21_protocol_anomalies.conf

lrwxr-xr-x 1 root wheel 76 May 17 14:01 modsecurity_crs_23_request_limits.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_23_request_limits.conf

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_crs_30_http_policy.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_30_http_policy.conf

lrwxr-xr-x 1 root wheel 72 May 17 14:01 modsecurity_crs_35_bad_robots.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_35_bad_robots.conf

lrwxr-xr-x 1 root wheel 77 May 17 14:01 modsecurity_crs_40_generic_attacks.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_40_generic_attacks.conf

lrwxr-xr-x 1 root wheel 83 May 17 14:01 modsecurity_crs_41_sql_injection_attacks.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_crs_41_xss_attacks.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_41_xss_attacks.conf

lrwxr-xr-x 1 root wheel 78 May 17 14:14 modsecurity_crs_42_comment_spam.conf -> /usr/local/apache/conf/crs/optional_rules/modsecurity_crs_42_comment_spam.conf

lrwxr-xr-x 1 root wheel 76 May 17 14:01 modsecurity_crs_42_tight_security.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_42_tight_security.conf

lrwxr-xr-x 1 root wheel 69 May 17 14:01 modsecurity_crs_45_trojans.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_45_trojans.conf

lrwxr-xr-x 1 root wheel 79 May 17 14:01 modsecurity_crs_47_common_exceptions.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_47_common_exceptions.conf

lrwxr-xr-x 1 root wheel 86 May 17 14:01 modsecurity_crs_48_local_exceptions.conf.example ->

/usr/local/apache/conf/crs/base_rules/modsecurity_crs_48_local_exceptions.conf.example

lrwxr-xr-x 1 root wheel 78 May 17 14:01 modsecurity_crs_49_inbound_blocking.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_49_inbound_blocking.conf

lrwxr-xr-x 1 root wheel 70 May 17 14:01 modsecurity_crs_50_outbound.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_50_outbound.conf

lrwxr-xr-x 1 root wheel 79 May 17 14:01 modsecurity_crs_59_outbound_blocking.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_59_outbound_blocking.conf

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_crs_60_correlation.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_60_correlation.conf

lrwxr-xr-x 1 root wheel 73 May 17 14:01 modsecurity_crs_60_customrules.conf -> /usr/local/apache/conf/crs/base_rules/modsecurity_crs_60_customrules.conf

 

3) Add the following line to your httpd.conf (assuming

you've placed the rule files into conf/crs/):

 

<IfModule security2_module>

Include conf/crs/modsecurity_crs_10_setup.conf

Include conf/crs/activated_rules/*.conf

</IfModule>

 

3) Restart web server.

 

4) Make sure your web sites are still running fine.

 

5) Simulate an attack against the web server. Then check

the attack was correctly logged in the Apache error log,

ModSecurity debug log (if you enabled it) and ModSecurity

audit log (if you enabled it).

 

# cp modsecurity_crs_10_setup.conf.example modsecurity_crs_10_setup.conf

#

 

# ln -s /etc/httpd/conf/crs/modsecurity_crs_10_setup.conf activated_rules/modsecurity_crs_10_setup.conf

 

# for FILE in `ls base_rules/`

do

ln -s /etc/httpd/conf/crs/base_rules/$FILE activated_rules/$FILE

done

 

# for FILE in `ls optional_rules/ | grep comment_spam`

do

ln -s /etc/httpd/conf/crs/optional_rules/$f activated_rules/$FILE

done

 

 

 

# ls -l activated_rules

total 84K

lrwxrwxrwx 1 root root 61 Sep 23 09:36 modsecurity_35_bad_robots.data -> /etc/httpd/conf/crs/base_rules/modsecurity_35_bad_robots.data

lrwxrwxrwx 1 root root 59 Sep 23 09:36 modsecurity_35_scanners.data -> /etc/httpd/conf/crs/base_rules/modsecurity_35_scanners.data

lrwxrwxrwx 1 root root 66 Sep 23 09:36 modsecurity_40_generic_attacks.data -> /etc/httpd/conf/crs/base_rules/modsecurity_40_generic_attacks.data

lrwxrwxrwx 1 root root 35 Sep 23 09:37 modsecurity_42_comment_spam.data -> /etc/httpd/conf/crs/optional_rules//

lrwxrwxrwx 1 root root 59 Sep 23 09:36 modsecurity_50_outbound.data -> /etc/httpd/conf/crs/base_rules/modsecurity_50_outbound.data

lrwxrwxrwx 1 root root 67 Sep 23 09:36 modsecurity_50_outbound_malware.data -> /etc/httpd/conf/crs/base_rules/modsecurity_50_outbound_malware.data

lrwxrwxrwx 1 root root 49 Sep 23 09:22 modsecurity_crs_10_setup.conf -> /etc/httpd/conf/crs/modsecurity_crs_10_setup.conf

lrwxrwxrwx 1 root root 74 Sep 23 09:36 modsecurity_crs_20_protocol_violations.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_20_protocol_violations.conf

lrwxrwxrwx 1 root root 73 Sep 23 09:36 modsecurity_crs_21_protocol_anomalies.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_21_protocol_anomalies.conf

lrwxrwxrwx 1 root root 69 Sep 23 09:36 modsecurity_crs_23_request_limits.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_23_request_limits.conf

lrwxrwxrwx 1 root root 66 Sep 23 09:36 modsecurity_crs_30_http_policy.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_30_http_policy.conf

lrwxrwxrwx 1 root root 65 Sep 23 09:36 modsecurity_crs_35_bad_robots.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_35_bad_robots.conf

lrwxrwxrwx 1 root root 70 Sep 23 09:36 modsecurity_crs_40_generic_attacks.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_40_generic_attacks.conf

lrwxrwxrwx 1 root root 76 Sep 23 09:36 modsecurity_crs_41_sql_injection_attacks.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf

lrwxrwxrwx 1 root root 66 Sep 23 09:36 modsecurity_crs_41_xss_attacks.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_41_xss_attacks.conf

lrwxrwxrwx 1 root root 35 Sep 23 09:37 modsecurity_crs_42_comment_spam.conf -> /etc/httpd/conf/crs/optional_rules//

lrwxrwxrwx 1 root root 69 Sep 23 09:36 modsecurity_crs_42_tight_security.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_42_tight_security.conf

lrwxrwxrwx 1 root root 62 Sep 23 09:36 modsecurity_crs_45_trojans.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_45_trojans.conf

lrwxrwxrwx 1 root root 72 Sep 23 09:36 modsecurity_crs_47_common_exceptions.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_47_common_exceptions.conf

lrwxrwxrwx 1 root root 79 Sep 23 09:36 modsecurity_crs_48_local_exceptions.conf.example -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_48_local_exceptions.conf.example

lrwxrwxrwx 1 root root 71 Sep 23 09:36 modsecurity_crs_49_inbound_blocking.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_49_inbound_blocking.conf

lrwxrwxrwx 1 root root 63 Sep 23 09:36 modsecurity_crs_50_outbound.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_50_outbound.conf

lrwxrwxrwx 1 root root 72 Sep 23 09:36 modsecurity_crs_59_outbound_blocking.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_59_outbound_blocking.conf

lrwxrwxrwx 1 root root 66 Sep 23 09:36 modsecurity_crs_60_correlation.conf -> /etc/httpd/conf/crs/base_rules/modsecurity_crs_60_correlation.conf

-rw-r--r-- 1 root root 5.6K Apr 17 07:24 README

 

# cat /etc/httpd/conf/httpd.conf

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

207 #

208 # Load config files from the config directory "/etc/httpd/conf.d".

209 #

210 Include conf.d/*.conf

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

 

# cat /etc/httpd/conf.d/mod_security.conf

# Example configuration file for the mod_security Apache module

 

LoadModule security2_module modules/mod_security2.so

LoadModule unique_id_module modules/mod_unique_id.so

 

<IfModule mod_security2.c>

# This is the ModSecurity Core Rules Set.

 

# Basic configuration goes in here

Include modsecurity.d/modsecurity_crs_10_config.conf

 

# Protocol violation and anomalies.

 

Include modsecurity.d/modsecurity_crs_20_protocol_violations.conf

Include modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf

 

# HTTP policy rules

 

Include modsecurity.d/modsecurity_crs_30_http_policy.conf

 

# Here comes the Bad Stuff...

 

Include modsecurity.d/modsecurity_crs_35_bad_robots.conf

Include modsecurity.d/modsecurity_crs_40_generic_attacks.conf

Include modsecurity.d/modsecurity_crs_45_trojans.conf

Include modsecurity.d/modsecurity_crs_50_outbound.conf

 

# Search engines and other crawlers. Only useful if you want to track

# Google / Yahoo et. al.

 

# Include modsecurity.d/modsecurity_crs_55_marketing.conf

 

# Put your local rules in here.

 

Include modsecurity.d/modsecurity_localrules.conf

</IfModule>

 

 

 

# service httpd restart

Stopping httpd: [FAILED]

Starting httpd: [ OK ]

 

# pgrep -lf httpd

16819 /usr/sbin/httpd

16822 /usr/sbin/httpd

16823 /usr/sbin/httpd

16824 /usr/sbin/httpd

16825 /usr/sbin/httpd

16826 /usr/sbin/httpd

16827 /usr/sbin/httpd

16828 /usr/sbin/httpd

16829 /usr/sbin/httpd

 

# cd /etc/httpd

# ls -l

drwxr-xr-x 3 root root 4.0K Sep 23 11:03 conf/

drwxr-xr-x 2 root root 4.0K Sep 23 11:08 conf.d/

lrwxrwxrwx 1 root root 19 Sep 22 22:30 logs -> ../../var/log/httpd/

drwxr-xr-x 3 root root 4.0K Sep 22 22:28 modsecurity.d/

lrwxrwxrwx 1 root root 27 Sep 22 22:30 modules -> ../../usr/lib/httpd/modules/

lrwxrwxrwx 1 root root 13 Sep 22 22:30 run -> ../../var/run/

 

 

[참고] 로그 기록에 대한 구조

 

----> ModSecurity(WAF) ----> Apache(WEB Server)

modsec_audit.log access_log

error_log

 

 

# cd logs (# cd /var/log/httpd)

# ls

access_log error_log.2 ssl_access_log.1 ssl_error_log.3

access_log.1 error_log.3 ssl_access_log.2 ssl_error_log.4

access_log.2 error_log.4 ssl_access_log.3 ssl_request_log

access_log.3 modsec_audit.log ssl_error_log ssl_request_log.1

error_log modsec_debug.log ssl_error_log.1 ssl_request_log.2

error_log.1 ssl_access_log ssl_error_log.2 ssl_request_log.3

 

 

[TERM1] # tail -0f access_log

[TERM2] # tail -0f error_log

[TERM3] # tail -0f modsec_audit.log

[TERM4] # tail -0f modsec_debug.log

 

 

 

 

 

 

웹 공격을 하기 위한 툴로 fimap을 사용한다.

 

(KaliLinux)

 

(주의) 2016년도 0601일 현재 fimap 프로그램의 plugins 설치가 되지 않음

따라서, 실습을 진행할 때 paros(in kalilinux) 툴을 사용하였다.

 

파이맵(fimap)

웹 애플리케이션에 로컬 또는 원격 파일 삽입(LFI and RFI) 버그를 자동으로 찾고 검사하고 공격하는 파이썬으로 만들어 툴

 

# fimap --install-plugins

fimap v.09 (For the Swarm)

:: Automatic LFI/RFI scanner and exploiter

:: by Iman Karim (fimap.dev@gmail.com)

 

Requesting list of plugins...

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

#LIST OF TRUSTED PLUGINS #

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

#[1] Weevils injector by Darren "Infodox" Martyn <infodox@insecurety.net> - At version 2 not installed. #

#[2] AES HTTP reverse shell by Darren "Infodox" Martyn <infodox@insecurety.net> - At version 1 not installed. #

#[q] Cancel and Quit. #

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

Choose a plugin to install: 1

Downloading plugin 'weevils' (http://85.214.72.67/fimap_plugins/weevils-0.2.tar.gz)...

Unpacking plugin...

Plugin 'Upload Weevely' installed successfully!

설치할 수 있는 plugins 두가지가 있다. 두가지 플러그인을 모두 설치하기 위해서는 두번 명령어를 수행하여 하나씩 설치하여야 한다.

 

# fimap --install-plugins

fimap v.09 (For the Swarm)

:: Automatic LFI/RFI scanner and exploiter

:: by Iman Karim (fimap.dev@gmail.com)

 

Requesting list of plugins...

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

#LIST OF TRUSTED PLUGINS #

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

#[1] Weevils injector by Darren "Infodox" Martyn <infodox@insecurety.net> - At version 2 has an UPDATE. #

#[2] AES HTTP reverse shell by Darren "Infodox" Martyn <infodox@insecurety.net> - At version 1 not installed. #

#[q] Cancel and Quit. #

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

Choose a plugin to install: 2

Downloading plugin 'aeshttp' (http://85.214.72.67/fimap_plugins/aeshttp-0.1.tar.gz)...

Unpacking plugin...

Plugin 'AES HTTP Reverse Shell Injector' installed successfully!

 

# fimap --help

fimap v.09 (For the Swarm)

:: Automatic LFI/RFI scanner and exploiter

:: by Iman Karim (fimap.dev@gmail.com)

 

Usage: ./fimap.py [options]

## Operating Modes:

-s , --single Mode to scan a single URL for FI errors.

Needs URL (-u). This mode is the default.

-m , --mass Mode for mass scanning. Will check every URL

from a given list (-l) for FI errors.

-g , --google Mode to use Google to aquire URLs.

Needs a query (-q) as google search query.

-H , --harvest Mode to harvest a URL recursivly for new URLs.

Needs a root url (-u) to start crawling there.

Also needs (-w) to write a URL list for mass mode.

-4 , --autoawesome With the AutoAwesome mode fimap will fetch all

forms and headers found on the site you defined

and tries to find file inclusion bugs thru them. Needs an

URL (-u).

## Techniques:

-b , --enable-blind Enables blind FI-Bug testing when no error messages are printed.

Note that this mode will cause lots of requests compared to the

default method. Can be used with -s, -m or -g.

-D , --dot-truncation Enables dot truncation technique to get rid of the suffix if

the default mode (nullbyte poison) failed. This mode can cause

tons of requests depending how you configure it.

By default this mode only tests windows servers.

Can be used with -s, -m or -g. Experimental.

-M , --multiply-term=X Multiply terminal symbols like '.' and '/' in the path by X.

## Variables:

-u , --url=URL The URL you want to test.

Needed in single mode (-s).

-l , --list=LIST The URL-LIST you want to test.

Needed in mass mode (-m).

-q , --query=QUERY The Google Search QUERY.

Example: 'inurl:include.php'

Needed in Google Mode (-g)

--skip-pages=X Skip the first X pages from the Googlescanner.

-p , --pages=COUNT Define the COUNT of pages to search (-g).

Default is 10.

--results=COUNT The count of results the Googlescanner should get per page.

Possible values: 10, 25, 50 or 100(default).

--googlesleep=TIME The time in seconds the Googlescanner should wait befor each

request to google. fimap will count the time between two requests

and will sleep if it's needed to reach your cooldown. Default is 5.

-w , --write=LIST The LIST which will be written if you have choosen

harvest mode (-H). This file will be opened in APPEND mode.

-d , --depth=CRAWLDEPTH The CRAWLDEPTH (recurse level) you want to crawl your target site

in harvest mode (-H). Default is 1.

-P , --post=POSTDATA The POSTDATA you want to send. All variables inside

will also be scanned for file inclusion bugs.

--cookie=COOKIES Define the cookie which should be send with each request.

Also the cookies will be scanned for file inclusion bugs.

Concatenate multiple cookies with the ';' character.

--ttl=SECONDS Define the TTL (in seconds) for requests. Default is 30 seconds.

--no-auto-detect Use this switch if you don't want to let fimap automaticly detect

the target language in blind-mode. In that case you will get some

options you can choose if fimap isn't sure which lang it is.

--bmin=BLIND_MIN Define here the minimum count of directories fimap should walk thru

in blind mode. The default number is defined in the generic.xml

--bmax=BLIND_MAX Define here the maximum count of directories fimap should walk thru.

--dot-trunc-min=700 The count of dots to begin with in dot-truncation mode.

--dot-trunc-max=2000 The count of dots to end with in dot-truncation mode.

--dot-trunc-step=50 The step size for each round in dot-truncation mode.

--dot-trunc-ratio=0.095 The maximum ratio to detect if dot truncation was successfull.

--dot-trunc-also-unix Use this if dot-truncation should also be tested on unix servers.

--force-os=OS Forces fimap to test only files for the OS.

OS can be 'unix' or 'windows'

## Attack Kit:

-x , --exploit Starts an interactive session where you can

select a target and do some action.

-T , --tab-complete Enables TAB-Completation in exploit mode. Needs readline module.

Use this if you want to be able to tab-complete thru remote

files\dirs. Eats an extra request for every 'cd' command.

## Disguise Kit:

-A , --user-agent=UA The User-Agent which should be sent.

--http-proxy=PROXY Setup your proxy with this option. But read this facts:

* The googlescanner will ignore the proxy to get the URLs,

but the pentest\attack itself will go thru proxy.

* PROXY should be in format like this: 127.0.0.1:8080

* It's experimental

--show-my-ip Shows your internet IP, current country and user-agent.

Useful if you want to test your vpn\proxy config.

## Plugins:

--plugins List all loaded plugins and quit after that.

-I , --install-plugins Shows some official exploit-mode plugins you can install

and\or upgrade.

## Other:

--update-def Checks and updates your definition files found in the

config directory.

--test-rfi A quick test to see if you have configured RFI nicely.

--merge-xml=XMLFILE Use this if you have another fimap XMLFILE you want to

include to your own fimap_result.xml.

-C , --enable-color Enables a colorful output. Works only in linux!

--force-run Ignore the instance check and just run fimap even if a lockfile

exists. WARNING: This may erase your fimap_results.xml file!

-v , --verbose=LEVEL Verbose level you want to receive.

LEVEL=3 -> Debug

LEVEL=2 -> Info(Default)

LEVEL=1 -> Messages

LEVEL=0 -> High-Level

--credits Shows some credits.

--greetings Some greetings ;)

-h , --help Shows this cruft.

## Examples:

1. Scan a single URL for FI errors:

./fimap.py -u 'http://localhost/test.php?file=bang&id=23'

2. Scan a list of URLS for FI errors:

./fimap.py -m -l '/tmp/urllist.txt'

3. Scan Google search results for FI errors:

./fimap.py -g -q 'inurl:include.php'

4. Harvest all links of a webpage with recurse level of 3 and

write the URLs to /tmp/urllist

./fimap.py -H -u 'http://localhost' -d 3 -w /tmp/urllist

 

 

 

 

# fimap -u 'http://192.168.20.200/test.php?file=bang&id=23'

fimap v.09 (For the Swarm)

:: Automatic LFI/RFI scanner and exploiter

:: by Iman Karim (fimap.dev@gmail.com)

 

SingleScan is testing URL: 'http://192.168.20.200/test.php?file=bang&id=23'

[08:37:31] [OUT] Inspecting URL 'http://192.168.20.200/test.php?file=bang&id=23'...

[08:37:31] [INFO] Fiddling around with URL...

[08:37:31] [WARN] HTTP Error 400: Bad Request

[08:37:31] [WARN] HTTP Error 400: Bad Request

Target URL isn't affected by any file inclusion bug :(

-> 파이맵은 파일 삽입 취약점이 있는지 검색한다.

-> 웹서버(웹방화벽)에서 로그를 확인한다.(출력 결과가 늦게 나올수 있다.)

-> fimap 명령어에 --force-run 옵션을 줄수도 있다.

# fimap --force-run -u "http://192.168.20.200/?p=2475"

 

 

wireshark을 통해 공격 패킷을 분석한다.

 

 

(linux200) Web Application Firewall

[TERM1] # tail -0f access_log

192.168.20.50 - - [12/Dec/2014:17:31:30 +0900] "GET /test.php?file=bang&id=LOmISkC5 HTTP/1.1" 400 302 "-" "fimap.googlecode.com/v09 (For the Swarm)"

192.168.20.50 - - [12/Dec/2014:17:31:30 +0900] "GET /test.php?file=W9YWiyO6&id=23 HTTP/1.1" 400 302 "-" "fimap.googlecode.com/v09 (For the Swarm)"

 

[TERM2] # tail -0f err_log

[Fri Dec 12 17:24:23 2014] [notice] caught SIGTERM, shutting down

[Fri Dec 12 17:24:23 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)

[Fri Dec 12 17:24:24 2014] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Dec 12 17:24:24 2014] [notice] ModSecurity for Apache/2.5.9 (http://www.modsecurity.org/) configured.

[Fri Dec 12 17:24:24 2014] [notice] Original server signature: Apache/2.2.22 (EL)

[Fri Dec 12 17:24:24 2014] [notice] Digest: generating secret for digest authentication ...

[Fri Dec 12 17:24:24 2014] [notice] Digest: done

[Fri Dec 12 17:24:25 2014] [notice] mod_python: Creating 4 session mutexes based on 256 max processes and 0 max threads.

[Fri Dec 12 17:24:25 2014] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Dec 12 17:24:25 2014] [notice] Apache/2.2.22 (Unix) DAV/2 PHP/5.1.6 mod_python/3.2.8 Python/2.4.3 mod_ssl/2.2.22 OpenSSL/0.9.8e-fips-rhel5 Apache/2.2.0 (Fedora) mod_perl/2.0.4 Perl/v5.8.8 configured -- resuming normal operations

[Fri Dec 12 17:26:41 2014] [notice] caught SIGTERM, shutting down

[Fri Dec 12 17:26:59 2014] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)

[Fri Dec 12 17:27:00 2014] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Dec 12 17:27:00 2014] [notice] ModSecurity for Apache/2.5.9 (http://www.modsecurity.org/) configured.

[Fri Dec 12 17:27:00 2014] [notice] Original server signature: Apache/2.2.22 (EL)

[Fri Dec 12 17:27:00 2014] [notice] Digest: generating secret for digest authentication ...

[Fri Dec 12 17:27:00 2014] [notice] Digest: done

[Fri Dec 12 17:27:01 2014] [notice] mod_python: Creating 4 session mutexes based on 256 max processes and 0 max threads.

[Fri Dec 12 17:27:01 2014] [error] SecServerSignature: original signature too short. Please set ServerTokens to Full.

[Fri Dec 12 17:27:01 2014] [notice] Apache/2.2.22 (Unix) DAV/2 PHP/5.1.6 mod_python/3.2.8 Python/2.4.3 mod_ssl/2.2.22 OpenSSL/0.9.8e-fips-rhel5 Apache/2.2.0 (Fedora) mod_perl/2.0.4 Perl/v5.8.8 configured -- resuming normal operations

[Fri Dec 12 17:31:30 2014] [error] [client 192.168.20.50] ModSecurity: Access denied with code 400 (phase 2). Pattern match "^[\\d\\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"] [hostname "192.168.20.200"] [uri "/test.php"] [unique_id "VIqn4sCoFMgAAB6IH7EAAAAA"]

[Fri Dec 12 17:31:30 2014] [error] [client 192.168.20.50] ModSecurity: Access denied with code 400 (phase 2). Pattern match "^[\\d\\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"] [hostname "192.168.20.200"] [uri "/test.php"] [unique_id "VIqn4sCoFMgAAB6JIAYAAAAB"]

 

 

 

[TERM3] # tail -0f modsec_audit.log

--d309977a-A--

[12/Dec/2014:17:31:30 +0900] VIqn4sCoFMgAAB6IH7EAAAAA 192.168.20.50 54678 192.168.20.200 80

--d309977a-B--

GET /test.php?file=bang&id=LOmISkC5 HTTP/1.1

Accept-Encoding: identity

Host: 192.168.20.200

Accept-Language: en-us,en;q=0.5

Connection: close

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

User-Agent: fimap.googlecode.com/v09 (For the Swarm)

 

--d309977a-F--

HTTP/1.1 400 Bad Request

Content-Length: 302

Connection: close

Content-Type: text/html; charset=iso-8859-1

 

--d309977a-H--

Message: Access denied with code 400 (phase 2). Pattern match "^[\d\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"]

Action: Intercepted (phase 2)

Apache-Handler: php5-script

Stopwatch: 1418373090833289 6370 (5782 6076 -)

Producer: ModSecurity for Apache/2.5.9 (http://www.modsecurity.org/); core ruleset/1.6.1.

Server: Apache/2.2.22 (EL)

 

--d309977a-K--

SecRule "REQUEST_METHOD" "@rx ^(?:GET|HEAD)$" "phase:2,chain,t:none,deny,log,auditlog,status:400,msg:'GET or HEAD requests with bodies',severity:2,id:960011,tag:PROTOCOL_VIOLATION/EVASION"

SecRule "&REQUEST_HEADERS:Content-Type" "@eq 0" "phase:2,pass,chain,t:none,log,auditlog,msg:'Request Containing Content, but Missing Content-Type header',id:960904,severity:4"

SecRule "REQUEST_HEADERS:Host" "@rx ^[\\d\\.]+$" "phase:2,t:none,deny,log,auditlog,status:400,msg:'Host header is a numeric IP address',severity:2,id:960017,tag:PROTOCOL_VIOLATION/IP_HOST"

SecRule "RESPONSE_STATUS" "@rx ^400$" "phase:5,t:none,chain,log,auditlog,pass,msg:'Invalid request',id:960913,severity:2"

 

--d309977a-Z--

 

--d309977a-A--

[12/Dec/2014:17:31:30 +0900] VIqn4sCoFMgAAB6JIAYAAAAB 192.168.20.50 54679 192.168.20.200 80

--d309977a-B--

GET /test.php?file=W9YWiyO6&id=23 HTTP/1.1

Accept-Encoding: identity

Host: 192.168.20.200

Accept-Language: en-us,en;q=0.5

Connection: close

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

User-Agent: fimap.googlecode.com/v09 (For the Swarm)

 

--d309977a-F--

HTTP/1.1 400 Bad Request

Content-Length: 302

Connection: close

Content-Type: text/html; charset=iso-8859-1

 

--d309977a-H--

Message: Access denied with code 400 (phase 2). Pattern match "^[\d\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"]

Action: Intercepted (phase 2)

Apache-Handler: php5-script

Stopwatch: 1418373090841735 612 (287 463 -)

Producer: ModSecurity for Apache/2.5.9 (http://www.modsecurity.org/); core ruleset/1.6.1.

Server: Apache/2.2.22 (EL)

 

--d309977a-K--

SecRule "REQUEST_METHOD" "@rx ^(?:GET|HEAD)$" "phase:2,chain,t:none,deny,log,auditlog,status:400,msg:'GET or HEAD requests with bodies',severity:2,id:960011,tag:PROTOCOL_VIOLATION/EVASION"

SecRule "&REQUEST_HEADERS:Content-Type" "@eq 0" "phase:2,pass,chain,t:none,log,auditlog,msg:'Request Containing Content, but Missing Content-Type header',id:960904,severity:4"

SecRule "REQUEST_HEADERS:Host" "@rx ^[\\d\\.]+$" "phase:2,t:none,deny,log,auditlog,status:400,msg:'Host header is a numeric IP address',severity:2,id:960017,tag:PROTOCOL_VIOLATION/IP_HOST"

SecRule "RESPONSE_STATUS" "@rx ^400$" "phase:5,t:none,chain,log,auditlog,pass,msg:'Invalid request',id:960913,severity:2"

 

--d309977a-Z--

 

 

 

[TERM4] # tail -0f modsec_debug.log

[12/Dec/2014:17:31:30 +0900] [192.168.20.200/sid#94ef4f8][rid#9a6e5e0][/test.php][1] Access denied with code 400 (phase 2). Pattern match "^[\d\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"]

[12/Dec/2014:17:31:30 +0900] [192.168.20.200/sid#94ef4f8][rid#9a6e5e0][/test.php][1] Access denied with code 400 (phase 2). Pattern match "^[\d\.]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/modsecurity_crs_21_protocol_anomalies.conf"] [line "60"] [id "960017"] [msg "Host header is a numeric IP address"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/IP_HOST"]

 

 

 

(원복) 실습이 끝나다면 다음과 같은 작업을 한다.

yum repository 지정 복원(별도로 생성된 *.repo 파일이 존재한다면)# cd /etc/yum.repos.d # vi utterramblings.repo (enabled=0)# vi hello.repo (enabled=0)

WAF 설정 파일 복원# cd /etc/httpd/conf.d # mv /etc/httpd/conf.d/mod_security.conf /etc/httpd

 

 

 

[과제] 여러가지 툴을 통해 웹 공격을 수행하고 웹방화벽에서 정상적으로 필터링되는지 확인(시간: 1시간 정도)

- 유튜브 동영상을 통해 확인한다.

- (EX) OWASP ZAP - OWASP 10대 취약점을 점검하는 취약점 스캐너

 

 

 


ModSecurity.hwp

TR-2008-003_ModSecurity_guide.pdf


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160803 SELinux  (0) 2016.08.03
20160803 소프트웨어 관리  (0) 2016.08.03
20160802 Snort  (0) 2016.08.02
20160801 IDS  (0) 2016.08.01
20160801 TCP Wrapper  (0) 2016.08.01
Posted by 22Hz
, |

 

 

 

Snort(Sniffer and More)

NIDS on CentOS 6.4/6.5

 

 

 

 

 

Firewall(방화벽) vs IDS(침입탐지시스템) vs IPS(침입차단시스템)

 

구분

IPS(침입차단시스템)

IDS(침입탐지시스템)

F/W(침입차단시스템)

연결 방법

In-Line

Mirror(TAP, Switch)

In-Line

차단 방법

자체

Reset Signal, 방화벽 연동

자체

on-way attack

탐지/차단

탐지

불가능

DDoS & Dos

탐지/차단

탐지

일부지원

서비스 중단 시 장애 극복

FOD를 통한 장애 극복

무관

HA, Fail Over를 통한 극복

실시간 네트워크 세션 감시

지원

지원

지원

Worm Virus

탐지/차단

탐지

불가능

NAT

지원 안됨

지원 안됨

지원함

다중포트

2개 구간

8개 구간

NIC 연결 추가 지원

장점

모든 패킷에 대해 자체 탐지 및 차단 모듈 지원으로 네트워크 보호

모든 패킷에 대해 자체 탐지 모듈 지원으로 네트워크 이상 징후 경고

서비스 및 객체 대한 접근 권한 정책을 구체적 규정하는 것이 가능하여 불필요한 서비스 사용 제한

단점

NAT등 방화벽 고유 기능 지원 불가로 사설 네트워크 구성시 제한

방화벽과 연동 방어를 통해 차단 가능함(독립적 차단 제하적)

IPPort 이외의 복합적으리고 정교한 공격 탐지 불가

 

 

 

 

 

IDS(Intrution Detection System)

Network defense or "protection" model- Planning : policy, rule- Prevention : IPS- Detection : IDS- Response : Email, Alert, Terminate session, report

Intrusion detection is the process of discovering, analyzing, and reporting unauthorized or damaging network or computer activities.

 

 

IDS(Intrution Detection System) 종류

N-IDS(Network based IDS) Network traffic is monitored by network-based intrusion detection systems.-> Open Source : Snort

H-IDS(Host based IDS)Computer processes are monnitored by host-based intrusion detection systems.-> Open Source : Tripwire

 

 

Snort(sniffer and more) 소개

 

Snort is Network Intrusion Detection System (NIDS). Snort can sniff your network and alert you based on his rule DB if there is an attack on your computers network. It is an opensource system that is build from tcpdump (linux sniffer tool).

 

Snort : an open source netework intrusion prevention and detection system. It uses a rule-based language combining signature, protocol and anomaly inspection methods.

 

Snort : the most widely deployed intrusion detection and prevention technology and it has become the standard technology worldwide in the industry.

 

A packet sniffer: capture and display packets from the network with different levels of detail on the console.

Packet logger: log data in text file.

Honeypot monitor: deceiving hostile parties.

A fast, flexible, small-footprint, open-source NIDS developed by the security commnunity.

Lead coder: Marty Roesch, now founder of Sourcefire(www.sourcefire.com).

Initially developed in late 1998 as a sniffer with consistent output, unlike protocol-dependent output of TCPDump.

 

 

 

 

 

 

 

 

사용시스템

- centos 6.X(6.4 or 6.5)

 

 

1. Snort 설치(Snort Installation)

 

INDEX

---------------------------

시스템 정보 확인

snort 관련 패키지 다운로드

snort rules 다운로드

snort 관련 패키지 컴파일

---------------------------

 

(1) 시스템 정보 확인

# uname -a

Linux ids.example.com 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

 

# cat /etc/redhat-release

CentOS release 6.4 (Final)

 

# cat /proc/cpuinfo

processor : 0

vendor_id : AuthenticAMD

cpu family : 21

model : 2

model name : AMD FX(tm)-6300 Six-Core Processor

stepping : 0

cpu MHz : 3507.009

cache size : 2048 KB

physical id : 0

siblings : 6

core id : 0

cpu cores : 6

apicid : 0

initial apicid : 0

fpu : yes

fpu_exception : yes

cpuid level : 13

wp : yes

flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good tsc_reliable nonstop_tsc aperfmperf unfair_spinlock pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic popcnt aes xsave avx f16c hypervisor lahf_lm cmp_legacy extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw xop fma4 tbm bmi1

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

 

# top -n 1 | egrep '(Mem:|Swap:)' (# free)

Mem: 881476k total, 553036k used, 328440k free, 23504k buffers

Swap: 4095992k total, 0k used, 4095992k free, 227476k cached

 

# df -h (# df -h -T)

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/vg_ids-lv_root

36G 3.8G 30G 12% /

tmpfs 431M 224K 431M 1% /dev/shm

/dev/sda1 485M 38M 423M 9% /boot

-> LVM(Logical Volume Manager)를 통해 구성이 되어져 있다.

 

 

# ifconfig (# ip addr)

eth0 Link encap:Ethernet HWaddr 00:0C:29:45:A1:D8

inet addr:192.168.20.203 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1d8/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:32 errors:0 dropped:0 overruns:0 frame:0

TX packets:17 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:11468 (11.1 KiB) TX bytes:1251 (1.2 KiB)

 

eth1 Link encap:Ethernet HWaddr 00:0C:29:45:A1:E2

inet addr:192.168.10.203 Bcast:192.168.10.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1e2/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:19 errors:0 dropped:0 overruns:0 frame:0

TX packets:6 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:2006 (1.9 KiB) TX bytes:468 (468.0 b)

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:16 errors:0 dropped:0 overruns:0 frame:0

TX packets:16 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:960 (960.0 b) TX bytes:960 (960.0 b)

 

 

 

 

(2) snort 관련 패키지 다운로드

 

다운로드 패키지 목록(Download snort packages)

 

====================예제========================================

snort-2.9.7.0.tar.gz www.snort.org(최신버전으로 받는다.)

daq-2.0.4.tar.gz www.snort.org(최신버전으로 받는다.)

libpcap-1.6.2.tar.gz www.tcpdump.org(최신버전으로 받는다.)

pcre-8.36.tar.bz2 www.pcre.org(최신버전으로 받는다.)

libdnet-1.12.tgz code.google.com/p/libdnet

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

 

패키지 다운로드 디렉토리 생성

# mkdir /snort && cd /snort

 

snort && daq 패키지 다운로드

http://www.snort.org 사이트에 들어 가서 최신 프로그램을 확인한다.

 

20150526 : daq-2.0.5.tar.gz / snort-2.9.7.3.tar.gz

20150908: daq-2.0.6.tar.gz / snort-2.9.7.5.tar.gz

20160106 : daq-2.0.6.tar.gz / snort-2.9.8.0.tar.gz

20160531 : daq-2.0.6.tar.gz / snort-2.9.8.2.tar.gz

20160802 : daq-2.0.6.tar.gz / snort-2.9.8.3.tar.gz

 

# wget https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

--2014-12-11 16:31:46-- https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

Resolving www.snort.org... 104.28.25.35, 104.28.24.35, 2400:cb00:2048:1::681c:1823, ...

Connecting to www.snort.org|104.28.25.35|:443... connected.

ERROR: certificate common name “ssl2000.cloudflare.com” doesn’t match requested host name “www.snort.org”.

To connect to www.snort.org insecurely, use ‘--no-check-certificate’.

 

# wget --no-check-certificate https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

--2014-12-11 16:31:46-- https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

Resolving www.snort.org... 104.28.25.35, 104.28.24.35, 2400:cb00:2048:1::681c:1823, ...

Connecting to www.snort.org|104.28.25.35|:443... connected.

ERROR: certificate common name “ssl2000.cloudflare.com” doesn’t match requested host name “www.snort.org”.

To connect to www.snort.org insecurely, use ‘--no-check-certificate’.

snort/daq-2.0.4.tar.gzheck-certificate https://www.snort.org/downloads/

--2014-12-11 16:33:44-- https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

Resolving www.snort.org... 104.28.24.35, 104.28.25.35, 2400:cb00:2048:1::681c:1923, ...

Connecting to www.snort.org|104.28.24.35|:443... connected.

WARNING: certificate common name “ssl2000.cloudflare.com” doesn’t match requested host name “www.snort.org”.

HTTP request sent, awaiting response... 302 Found

Location: https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/830/original/daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418286827&Signature=%2F9yiNQ2GbvnONASKekS4tbVQePM%3D [following]

--2014-12-11 16:33:46-- https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/830/original/daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418286827&Signature=%2F9yiNQ2GbvnONASKekS4tbVQePM%3D

Resolving s3.amazonaws.com... 54.231.244.8

Connecting to s3.amazonaws.com|54.231.244.8|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 495316 (484K) [,binary/octet-stream]

Saving to: “daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418286827&Signature=%2F9yiNQ2GbvnONASKekS4tbVQePM=”

 

100%[=========================================>] 495,316 136K/s in 3.6s

 

2014-12-11 16:33:50 (136 KB/s) - “daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418286827&Signature=%2F9yiNQ2GbvnONASKekS4tbVQePM=” saved [495316/495316]

 

# ls

daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418286827&Signature=%2F9yiNQ2GbvnONASKekS4tbVQePM=

 

# rm -rf daq*

#

 

# wget --no-check-certificate https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz \

-O daq-2.0.4.tar.gz

--2014-12-11 16:37:26-- https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

Resolving www.snort.org... failed: Name or service not known.

wget: unable to resolve host address “www.snort.org”

snort/daq-2.0.4.tar.gz -O daq-2.0.4.tar.gzps://www.snort.org/downloads/s

--2014-12-11 16:37:48-- https://www.snort.org/downloads/snort/daq-2.0.4.tar.gz

Resolving www.snort.org... 104.28.24.35, 104.28.25.35, 2400:cb00:2048:1::681c:1923, ...

Connecting to www.snort.org|104.28.24.35|:443... connected.

WARNING: certificate common name “ssl2000.cloudflare.com” doesn’t match requested host name “www.snort.org”.

HTTP request sent, awaiting response... 302 Found

Location: https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/830/original/daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418287071&Signature=6baO407gh69zPNZDgydKaYKn7p8%3D [following]

--2014-12-11 16:37:49-- https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/830/original/daq-2.0.4.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418287071&Signature=6baO407gh69zPNZDgydKaYKn7p8%3D

Resolving s3.amazonaws.com... 54.231.244.0

Connecting to s3.amazonaws.com|54.231.244.0|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 495316 (484K) [,binary/octet-stream]

Saving to: “daq-2.0.4.tar.gz”

 

100%[=========================================>] 495,316 110K/s in 4.4s

 

2014-12-11 16:37:56 (110 KB/s) - “daq-2.0.4.tar.gz” saved [495316/495316]

 

 

 

 

# wget --no-check-certificate https://www.snort.org/downloads/snort/snort-2.9.7.0.tar.gz \

-O snort-2.9.7.0.tar.gz

--2014-12-11 16:40:11-- https://www.snort.org/downloads/snort/snort-2.9.7.0.tar.gz

Resolving www.snort.org... 104.28.24.35, 104.28.25.35, 2400:cb00:2048:1::681c:1923, ...

Connecting to www.snort.org|104.28.24.35|:443... connected.

WARNING: certificate common name “ssl2000.cloudflare.com” doesn’t match requested host name “www.snort.org”.

HTTP request sent, awaiting response... 302 Found

Location: https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/819/original/snort-2.9.7.0.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418287214&Signature=20oRt6vZbNqfINNT8llYTTq3%2Bxc%3D [following]

--2014-12-11 16:40:12-- https://s3.amazonaws.com/snort-org-site/production/release_files/files/000/000/819/original/snort-2.9.7.0.tar.gz?AWSAccessKeyId=AKIAIXACIED2SPMSC7GA&Expires=1418287214&Signature=20oRt6vZbNqfINNT8llYTTq3%2Bxc%3D

Resolving s3.amazonaws.com... 54.231.244.0

Connecting to s3.amazonaws.com|54.231.244.0|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 6340553 (6.0M) [,binary/octet-stream]

Saving to: “snort-2.9.7.0.tar.gz”

 

100%[=========================================>] 6,340,553 254K/s in 18s

 

2014-12-11 16:40:31 (340 KB/s) - “snort-2.9.7.0.tar.gz” saved [6340553/6340553]

 

libpcap 패키지 다운로드

http://www.tcpdump.org 사이트에 접속하여 최신의 패키지를 다운로드 한다.

 

20150526 : libpcap-1.7.3.tar.gz

2015 0908: libpcap-1.7.4.tar.gz

2016 0106: libpcap-1.7.4.tar.gz

2016 0531: libpcap-1.7.4.tar.gz

 

# wget http://www.tcpdump.org/release/libpcap-1.6.2.tar.gz

--2014-12-11 16:45:01-- http://www.tcpdump.org/release/libpcap-1.6.2.tar.gz

Resolving www.tcpdump.org... 192.139.46.66, 69.4.231.52, 132.213.238.6, ...

Connecting to www.tcpdump.org|192.139.46.66|:80... connected.

HTTP request sent, awaiting response... 200 OK

Length: 651237 (636K) [application/x-gzip]

Saving to: “libpcap-1.6.2.tar.gz”

 

100%[=========================================>] 651,237 28.9K/s in 15s

 

2014-12-11 16:45:16 (43.6 KB/s) - “libpcap-1.6.2.tar.gz” saved [651237/651237]

 

pcre 패키지 다운로드

http://sourceforge.net/projects/pcre/files/pcre 사이트에 접속하여 최신의 패키지를 다운로드 한다.

 

20150526 : pcre-8.37.tar.gz

20150908 : pcre-8.37.tar.gz

20160106 : pcre-8.37.tar.gz

20160531 : pcre-8.38.tar.gz

 

# wget http://sourceforge.net/projects/pcre/files/pcre/8.36/pcre-8.36.tar.gz/download

--2014-12-11 16:48:25-- http://sourceforge.net/projects/pcre/files/pcre/8.36/pcre-8.36.tar.gz/download

Resolving sourceforge.net... 216.34.181.60

Connecting to sourceforge.net|216.34.181.60|:80... connected.

HTTP request sent, awaiting response... 302 Found

Location: http://downloads.sourceforge.net/project/pcre/pcre/8.36/pcre-8.36.tar.gz?r=&ts=1418284108&use_mirror=jaist [following]

--2014-12-11 16:48:26-- http://downloads.sourceforge.net/project/pcre/pcre/8.36/pcre-8.36.tar.gz?r=&ts=1418284108&use_mirror=jaist

Resolving downloads.sourceforge.net... 216.34.181.59

Connecting to downloads.sourceforge.net|216.34.181.59|:80... connected.

HTTP request sent, awaiting response... 302 Found

Location: http://jaist.dl.sourceforge.net/project/pcre/pcre/8.36/pcre-8.36.tar.gz [following]

--2014-12-11 16:48:27-- http://jaist.dl.sourceforge.net/project/pcre/pcre/8.36/pcre-8.36.tar.gz

Resolving jaist.dl.sourceforge.net... 150.65.7.130, 2001:df0:2ed:feed::feed

Connecting to jaist.dl.sourceforge.net|150.65.7.130|:80... connected.

HTTP request sent, awaiting response... 200 OK

Length: 2009464 (1.9M) [application/x-gzip]

Saving to: “pcre-8.36.tar.gz.1”

 

100%[=========================================>] 2,009,464 502K/s in 3.9s

 

2014-12-11 16:48:31 (502 KB/s) - “pcre-8.36.tar.gz.1” saved [2009464/2009464]

 

libdnet 패키지 다운로드

https://code.google.com/p/libdnet/ 사이트에 접속하여 최신의 패키지를 다운로드 한다.

 

20150526 : libdnet-1.12.tgz

20150908 : libdnet-1.12.tgz

20160106 : libdnet-1.12.tar.gz

20160531 : libdnet-1.12.tar.gz

 

# cd /snort

# wget https://github.com/dugsong/libdnet/archive/libdnet-1.12.tar.gz -O libdnet-1.12.tar.gz

--2016-01-06 22:15:11-- https://github.com/dugsong/libdnet/archive/libdnet-1.12.tar.gz

Resolving github.com... 192.30.252.130

Connecting to github.com|192.30.252.130|:443... connected.

HTTP request sent, awaiting response... 302 Found

Location: https://codeload.github.com/dugsong/libdnet/tar.gz/libdnet-1.12 [following]

--2016-01-06 22:15:12-- https://codeload.github.com/dugsong/libdnet/tar.gz/libdnet-1.12

Resolving codeload.github.com... 192.30.252.147

Connecting to codeload.github.com|192.30.252.147|:443... connected.

HTTP request sent, awaiting response... 200 OK

Length: 959945 (937K) [application/x-gzip]

Saving to: `libdnet-1.12'

 

100%[=================================================>] 959,945 295K/s in 3.2s

 

2016-01-06 22:15:16 (295 KB/s) - `libdnet-1.12' saved [959945/959945]

 

# ls

daq-2.0.6.tar.gz libpcap-1.7.4.tar.gz snort-2.9.8.0.tar.gz

libdnet-master.zip pcre-8.37.tar.gz

 

 

 

 

 

 

(3) snort rules 다운로드(Download snort rules packages)

 

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

oinkmaster-1.2.0.rpm www.rpmfind.net/rpm.pbone.net

snortrules-snapshot-2956.tar.gz www.snort.org

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

 

 

oinkmaster 파일 다운로드(실습에서는 rpm 파일을 받는다.)

(source code 받는 경우)

# wget http://sourceforge.net/projects/oinkmaster/files/oinkmaster/1.2/oinkmaster-1.2.tar.gz/download

 

or

 

(rpm 파일 받는 경우)

# wget ftp://ftp.pbone.net/mirror/ftp.sourceforge.net/pub/sourceforge/s/sn/snortsas/oinkmaster-1.2-0.noarch.rpm

 

 

 

snortrules 파일 다운로드

(주의) 반드시 www.snort.org 사이트에 무료계정을 등록한다.

 

20150526 : snortrules-snapshot-2973.tar.gz

20150908 : snortrules-snapshot-2975.tar.gz

20160106 : snortrules-snapshot-2980.tar.gz

20160531 : snortrules-snapshot-2982.tar.gz

 

# wget --no-check-certificate \

https://www.snort.org/downloads/registered/snortrules-snapshot-2970.tar.gz \

-O snortrules-snapshot-2970.tar.gz

 

# ls

daq-2.0.4.tar.gz oinkmaster-1.2.tar.gz snortrules-snapshot-2970.tar.gz

libdnet-1.12.tgz pcre-8.36.tar.gz

libpcap-1.6.2.tar.gz snort-2.9.7.0.tar.gz

-> (주의) snortrules-snapshot-*.tar.gz 파일은 반드시 file 명령어를 통해 확인해 봐야 한다.

만약 gzip으로 압축된 파일이 아니라고 나오는 경우(HTML document text)에는 직접 받아서

서버에 올려야 한다.

(비정상)

# file snortrules-snopshot-*.tar.gz

snortrules-snapshot-2975.tar.gz: HTML document text

(정상)

# file snortrules-snopshot-*.tar.gz

snortrules-snapshot-2980.tar.gz: gzip compressed data, from Unix, last modified:....

 

(4) 패키지 검파일(How to compile the packages)

 

패키지 설치 순서(Package installation order)

==============예제=============

oinkmaster-1.2.tar.gz

snortrules-snapshot-2970.tar.gz

libpcap-1.6.2.tar.gz

pcre-8.36.tar.gz

libdnet-1.12.tgz

daq-2.0.4.tar.gz

snort-2.9.7.0.tar.gz

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

 

 

패키지 검파일 방법

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

# tar xvzf <PKG>

# cd <PKG>

# ./configure

# make

# make install

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

 

[참고] configure/make/make install

 

 

선수 패키지 설치

# yum -y install gcc flex bison zlib zlib-devel gcc-c++

Loaded plugins: fastestmirror, refresh-packagekit, security

Loading mirror speeds from cached hostfile

* base: ftp.kaist.ac.kr

* extras: ftp.kaist.ac.kr

* updates: ftp.kaist.ac.kr

base | 3.7 kB 00:00

extras | 3.4 kB 00:00

updates | 3.4 kB 00:00

Setting up Install Process

Package zlib-1.2.3-29.el6.x86_64 already installed and latest version

Resolving Dependencies

--> Running transaction check

---> Package bison.x86_64 0:2.4.1-5.el6 will be installed

---> Package flex.x86_64 0:2.5.35-9.el6 will be installed

---> Package gcc.x86_64 0:4.4.7-11.el6 will be installed

--> Processing Dependency: libgomp = 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64

--> Processing Dependency: cpp = 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64

--> Processing Dependency: libgcc >= 4.4.7-11.el6 for package: gcc-4.4.7-11.el6.x86_64

--> Processing Dependency: glibc-devel >= 2.2.90-12 for package: gcc-4.4.7-11.el6.x86_64

--> Processing Dependency: cloog-ppl >= 0.15 for package: gcc-4.4.7-11.el6.x86_64

---> Package zlib-devel.x86_64 0:1.2.3-29.el6 will be installed

--> Running transaction check

---> Package cloog-ppl.x86_64 0:0.15.7-1.2.el6 will be installed

--> Processing Dependency: libppl_c.so.2()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64

--> Processing Dependency: libppl.so.7()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64

---> Package cpp.x86_64 0:4.4.7-11.el6 will be installed

--> Processing Dependency: libmpfr.so.1()(64bit) for package: cpp-4.4.7-11.el6.x86_64

---> Package glibc-devel.x86_64 0:2.12-1.149.el6 will be installed

--> Processing Dependency: glibc-headers = 2.12-1.149.el6 for package: glibc-devel-2.12-1.149.el6.x86_64

--> Processing Dependency: glibc = 2.12-1.149.el6 for package: glibc-devel-2.12-1.149.el6.x86_64

--> Processing Dependency: glibc-headers for package: glibc-devel-2.12-1.149.el6.x86_64

---> Package libgcc.x86_64 0:4.4.7-3.el6 will be updated

---> Package libgcc.x86_64 0:4.4.7-11.el6 will be an update

---> Package libgomp.x86_64 0:4.4.7-3.el6 will be updated

---> Package libgomp.x86_64 0:4.4.7-11.el6 will be an update

--> Running transaction check

---> Package glibc.x86_64 0:2.12-1.107.el6 will be updated

--> Processing Dependency: glibc = 2.12-1.107.el6 for package: glibc-common-2.12-1.107.el6.x86_64

---> Package glibc.x86_64 0:2.12-1.149.el6 will be an update

---> Package glibc-headers.x86_64 0:2.12-1.149.el6 will be installed

--> Processing Dependency: kernel-headers >= 2.2.1 for package: glibc-headers-2.12-1.149.el6.x86_64

--> Processing Dependency: kernel-headers for package: glibc-headers-2.12-1.149.el6.x86_64

---> Package mpfr.x86_64 0:2.4.1-6.el6 will be installed

---> Package ppl.x86_64 0:0.10.2-11.el6 will be installed

--> Running transaction check

---> Package glibc-common.x86_64 0:2.12-1.107.el6 will be updated

---> Package glibc-common.x86_64 0:2.12-1.149.el6 will be an update

---> Package kernel-headers.x86_64 0:2.6.32-504.1.3.el6 will be installed

--> Finished Dependency Resolution

 

Dependencies Resolved

 

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

Package Arch Version Repository Size

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

Installing:

bison x86_64 2.4.1-5.el6 base 637 k

flex x86_64 2.5.35-9.el6 base 285 k

gcc x86_64 4.4.7-11.el6 base 10 M

zlib-devel x86_64 1.2.3-29.el6 base 44 k

Installing for dependencies:

cloog-ppl x86_64 0.15.7-1.2.el6 base 93 k

cpp x86_64 4.4.7-11.el6 base 3.7 M

glibc-devel x86_64 2.12-1.149.el6 base 983 k

glibc-headers x86_64 2.12-1.149.el6 base 611 k

kernel-headers x86_64 2.6.32-504.1.3.el6 updates 3.3 M

mpfr x86_64 2.4.1-6.el6 base 157 k

ppl x86_64 0.10.2-11.el6 base 1.3 M

Updating for dependencies:

glibc x86_64 2.12-1.149.el6 base 3.8 M

glibc-common x86_64 2.12-1.149.el6 base 14 M

libgcc x86_64 4.4.7-11.el6 base 102 k

libgomp x86_64 4.4.7-11.el6 base 133 k

 

Transaction Summary

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

Install 11 Package(s)

Upgrade 4 Package(s)

 

Total download size: 39 M

Downloading Packages:

(1/15): bison-2.4.1-5.el6.x86_64.rpm | 637 kB 00:01

(2/15): cloog-ppl-0.15.7-1.2.el6.x86_64.rpm | 93 kB 00:00

(3/15): cpp-4.4.7-11.el6.x86_64.rpm | 3.7 MB 00:09

(4/15): flex-2.5.35-9.el6.x86_64.rpm | 285 kB 00:00

(5/15): gcc-4.4.7-11.el6.x86_64.rpm | 10 MB 00:10

(6/15): glibc-2.12-1.149.el6.x86_64.rpm | 3.8 MB 00:03

(7/15): glibc-common-2.12-1.149.el6.x86_64.rpm | 14 MB 00:09

(8/15): glibc-devel-2.12-1.149.el6.x86_64.rpm | 983 kB 00:00

(9/15): glibc-headers-2.12-1.149.el6.x86_64.rpm | 611 kB 00:00

(10/15): kernel-headers-2.6.32-504.1.3.el6.x86_64.rpm | 3.3 MB 00:03

(11/15): libgcc-4.4.7-11.el6.x86_64.rpm | 102 kB 00:00

(12/15): libgomp-4.4.7-11.el6.x86_64.rpm | 133 kB 00:00

(13/15): mpfr-2.4.1-6.el6.x86_64.rpm | 157 kB 00:00

(14/15): ppl-0.10.2-11.el6.x86_64.rpm | 1.3 MB 00:01

(15/15): zlib-devel-1.2.3-29.el6.x86_64.rpm | 44 kB 00:00

-----------------------------------------------------------------------------------

Total 962 kB/s | 39 MB 00:41

warning: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: NOKEY

Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

Importing GPG key 0xC105B9DE:

Userid : CentOS-6 Key (CentOS 6 Official Signing Key) <centos-6-key@centos.org>

Package: centos-release-6-4.el6.centos.10.x86_64 (@anaconda-CentOS-201303020151.x86_64/6.4)

From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6

Running rpm_check_debug

Running Transaction Test

Transaction Test Succeeded

Running Transaction

Updating : libgcc-4.4.7-11.el6.x86_64 1/19

Updating : glibc-2.12-1.149.el6.x86_64 2/19

Updating : glibc-common-2.12-1.149.el6.x86_64 3/19

Updating : libgomp-4.4.7-11.el6.x86_64 4/19

Installing : mpfr-2.4.1-6.el6.x86_64 5/19

Installing : cpp-4.4.7-11.el6.x86_64 6/19

Installing : ppl-0.10.2-11.el6.x86_64 7/19

Installing : cloog-ppl-0.15.7-1.2.el6.x86_64 8/19

Installing : kernel-headers-2.6.32-504.1.3.el6.x86_64 9/19

Installing : glibc-headers-2.12-1.149.el6.x86_64 10/19

Installing : glibc-devel-2.12-1.149.el6.x86_64 11/19

Installing : gcc-4.4.7-11.el6.x86_64 12/19

Installing : bison-2.4.1-5.el6.x86_64 13/19

Installing : flex-2.5.35-9.el6.x86_64 14/19

Installing : zlib-devel-1.2.3-29.el6.x86_64 15/19

Cleanup : libgomp-4.4.7-3.el6.x86_64 16/19

Cleanup : glibc-2.12-1.107.el6.x86_64 17/19

Cleanup : glibc-common-2.12-1.107.el6.x86_64 18/19

Cleanup : libgcc-4.4.7-3.el6.x86_64 19/19

Verifying : glibc-common-2.12-1.149.el6.x86_64 1/19

Verifying : gcc-4.4.7-11.el6.x86_64 2/19

Verifying : glibc-2.12-1.149.el6.x86_64 3/19

Verifying : bison-2.4.1-5.el6.x86_64 4/19

Verifying : glibc-headers-2.12-1.149.el6.x86_64 5/19

Verifying : glibc-devel-2.12-1.149.el6.x86_64 6/19

Verifying : libgcc-4.4.7-11.el6.x86_64 7/19

Verifying : libgomp-4.4.7-11.el6.x86_64 8/19

Verifying : flex-2.5.35-9.el6.x86_64 9/19

Verifying : mpfr-2.4.1-6.el6.x86_64 10/19

Verifying : kernel-headers-2.6.32-504.1.3.el6.x86_64 11/19

Verifying : zlib-devel-1.2.3-29.el6.x86_64 12/19

Verifying : cpp-4.4.7-11.el6.x86_64 13/19

Verifying : ppl-0.10.2-11.el6.x86_64 14/19

Verifying : cloog-ppl-0.15.7-1.2.el6.x86_64 15/19

Verifying : glibc-2.12-1.107.el6.x86_64 16/19

Verifying : glibc-common-2.12-1.107.el6.x86_64 17/19

Verifying : libgomp-4.4.7-3.el6.x86_64 18/19

Verifying : libgcc-4.4.7-3.el6.x86_64 19/19

 

Installed:

bison.x86_64 0:2.4.1-5.el6 flex.x86_64 0:2.5.35-9.el6

gcc.x86_64 0:4.4.7-11.el6 zlib-devel.x86_64 0:1.2.3-29.el6

 

Dependency Installed:

cloog-ppl.x86_64 0:0.15.7-1.2.el6 cpp.x86_64 0:4.4.7-11.el6

glibc-devel.x86_64 0:2.12-1.149.el6 glibc-headers.x86_64 0:2.12-1.149.el6

kernel-headers.x86_64 0:2.6.32-504.1.3.el6 mpfr.x86_64 0:2.4.1-6.el6

ppl.x86_64 0:0.10.2-11.el6

 

Dependency Updated:

glibc.x86_64 0:2.12-1.149.el6 glibc-common.x86_64 0:2.12-1.149.el6

libgcc.x86_64 0:4.4.7-11.el6 libgomp.x86_64 0:4.4.7-11.el6

 

Complete!

 

 

 

(4-1) oinkmaster 패키지 설치

# cd /snort

# tar xvzf oinkmaster-1.2.tar.gz

 

 

(4-2) snortrules 압축해제

# mkdir snortrules

# mv snortrules-snapshot-2970.tar.gz snortrules

# ls snortrules

 

(4-3) libpcap 컴파일 & 설치

# tar xvzf libpcap*.tar.gz

# cd libpcap-1.6.2

# ./configure

# make

# make install

 

[참고] # ./configure --help

[참고] # ./configure > /tmp/libpcap.config 2>&1

[참고] # ./configure && make && make install

[참고] # time ./configure

[참고] # ./configure ; echo $?

 

 

(4-4) pcre 컴파일 & 설치

 

a.tar.gz : # tar xvzf a.tar.gz (# gunzip a.tar.gz ; # tar xvf a.tar)

a.tar.bz2: # tar xvjf a.tar.bz2 (# bunzip2 a.tar.bz2; # tar xvf a.tar)

 

# cd /snort

# tar xvzf pcre-8.36.tar.gz

# cd pcre-8.36

# ./configure

# make

# make install

 

(4-5) libdnet 컴파일 & 설치

# cd /snort

# tar xvzf libdnet-1.12.tar.gz

# cd libdnet-1.12

# ./configure

# make

# make install

 

(4-6) daq 컴파일 & 설치

# cd /snort

# tar xvzf daq-2.0.4.tar.gz

# cd daq-2.0.4

# ./configure

# make

# make install

 

(4-7) snort 컴파일 & 설치

# cd /snort

# tar xvzf snort-2.9.7.0.tar.gz

# cd snort-2.9.7.0

# ./configure (주의) (snort 2.9.7.5 이상) ./configure --enable-sourcefire

# make

# make install

 

 

 

 

(5) Test Snort

 

interface mode 변경 및 snort 버전 확인

 

(무선)

- Managed mode ) # airmon-ng stop wlan0

- Monitor mode ) # airmon-ng start wlan0

(유선)

- Non promisc mode ) # ifconfig eth0 -promisc

- promisc mode ) # ifconfig eth0 promisc

 

# ifconfig eth0 promisc

# ifconfig eth0

eth0 Link encap:Ethernet HWaddr 00:0C:29:8D:B0:53

inet addr:192.168.10.203 Bcast:192.168.10.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe8d:b053/64 Scope:Link

UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1

RX packets:433 errors:0 dropped:0 overruns:0 frame:0

TX packets:177 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:57168 (55.8 KiB) TX bytes:12204 (11.9 KiB)

 

# which snort

/usr/local/bin/snort

 

# snort -V

,,_ -*> Snort! <*-

o" )~ Version 2.9.7.5 GRE (Build 262)

'''' By Martin Roesch & The Snort Team: http://www.snort.org/contact#team

Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved.

Copyright (C) 1998-2013 Sourcefire, Inc., et al.

Using libpcap version 1.7.4

Using PCRE version: 8.37 2015-04-28

Using ZLIB version: 1.2.3

or

 

,,_ -*> Snort! <*-

o" )~ Version 2.9.8.2 GRE (Build 335)

'''' By Martin Roesch & The Snort Team: http://www.snort.org/contact#team

Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved.

Copyright (C) 1998-2013 Sourcefire, Inc., et al.

Using libpcap version 1.7.4

Using PCRE version: 8.38 2015-11-23

Using ZLIB version: 1.2.3

 

 

 

 

 

2. 참고

 

참고 동영상

http://www.youtube.com/watch?v=DYBfCyd6cC0

 

 

snort rules generate => tools

snort(IDS) + preventing => IPS

snort -> DB -> WEB => tools

 

 

 

 

2. snort rules & configuration

 

디렉토리 생성 및 파일 생성

# mkdir -p /etc/snort/rules

# mkdir /var/log/snort /var/log/barnyard2 /usr/local/lib/snort_dynamicrules

 

# useradd snort /* 사용자가 미리 존재할 수 있다. ids.example.com 설치시 사용자 추가 */

# chown -R snort:snort /etc/snort /var/log/snort /var/log/barnyard2

 

 

setup snort rules

# cd /snort/snortrules

# tar xvzf snortrules-snapshot-*.tar.gz -C /etc/snort /* -C : change directory */

-> 출력 내용 생략

 

# cp -r /etc/snort/etc/* /etc/snort

 

# touch /etc/snort/rules/white_list.rules

# touch /etc/snort/rules/black_list.rules

 

# chown -R snort:snort /etc/snort

#

 

snort main file - snort.conf

# vi /etc/snort/snort.conf

[수정전]

45 ipvar HOME_NET any

104 var RULE_PATH ../rules

105 var SO_RULE_PATH ../so_rules

106 var PREPROC_RULE_PATH ../preproc_rules

109 var WHITE_LIST_PATH ../rules

110 var BLACK_LIST_PATH ../rules

519 # output alert_unified2: filename snort.alert, limit 128, nostamp

520 # output log_unified2: filename snort.log, limit 128, nostamp

[수정후]

45 ipvar HOME_NET 192.168.20.0/24

104 var RULE_PATH /etc/snort/rules

105 var SO_RULE_PATH /etc/snort/so_rules

106 var PREPROC_RULE_PATH /etc/snort/preproc_rules

109 var WHITE_LIST_PATH /etc/snort/rules

110 var BLACK_LIST_PATH /etc/snort/rules

519 output alert_unified2: filename snort.alert, limit 128, nostamp

520 output log_unified2: filename snort.log, limit 128, nostamp

-> 위와 같은 부분을 편집한다.

 

snort init script(EX: startup script)

# cp /snort/snort-*/rpm/snortd /etc/init.d/snortd

# chmod 755 /etc/init.d/snortd

# cat /etc/init.d/snortd | more

.....

# Source the local configuration file

. /etc/sysconfig/snort

.....

if [ "$CONF"X = "X" ]; then

CONF="-c /etc/snort/snort.conf"

else

CONF="-c $CONF"

fi

.....

if [ "$LOGDIR"X = "X" ]; then

LOGDIR=/var/log/snort

fi

.....

daemon /usr/sbin/snort $ALERTMODE $BINARY_LOG $NO_PACKET_LOG $DUMP_APP -D $PRINT_INTERFACE -i $i -u $USER -g $GROUP $CONF -l $LOGDIR/$i $PASS_FIRST $BPFFILE $BPF

done

.....

 

# cp /snort/snort-*/rpm/snort.sysconfig /etc/sysconfig/snort

# cat /etc/sysconfig/snort

-> 확인 정도만 한다.

# ln -s /usr/local/bin/snort /usr/sbin/snort

#

 

# chown -R snort:snort /var/log/snort

# chown snort:snort /usr/local/bin/snort

 

[참고] 새로운 서비스 등록 절차

# vi /etc/init.d/snortd

# chmod 700 /etc/init.d/snortd

# chown snort:snort /etc/init.d/snortd

# chkconfig --add snortd

 

# chkconfig --add snortd

# chkconfig --list snortd

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

 

# service snortd start

Starting snort: Spawning daemon child...

My daemon child 25853 lives...

Daemon parent exiting (0)

[ OK ]

 

# pgrep -lf snort

25853 /usr/sbin/snort -A fast -b -d -D -i eth0 -u snort -g snort -c /etc/snort/snort.conf -l /var/log/snort

 

-A alert-mode

Alert using the specified alert-mode. Valid alert modes include

fast, full, none, and unsock. Fast writes alerts to the default

"alert" file in a single-line, syslog style alert message. Full

writes the alert to the "alert" file with the full decoded

header as well as the alert message. None turns off alerting.

Unsock is an experimental mode that sends the alert information

out over a UNIX socket to another process that attaches to that

socket.

 

-b Log packets in a tcpdump(1) formatted file. All packets are

logged in their native binary state to a tcpdump formatted log

file named with the snort start timestamp and "snort.log". This

option results in much faster operation of the program

since it doesn’t have to spend time in the packet binary->text

converters. Snort can keep up pretty well with 100Mbps networks

in ’-b’ mode. To choose an alternate name for the binary log

file, use the ’-L’ switch.

 

-d Dump the application layer data when displaying packets in ver-

bose or packet logging mode.

 

-D Run Snort in daemon mode. Alerts are sent to

/var/log/snort/alert unless otherwise specified.

 

-i interface

Sniff packets on interface.

 

-u user

Change the user/UID Snort runs under to user after initialization.

 

-g group

Change the group/GID Snort runs under to group after initializa-

tion. This switch allows Snort to drop root privileges after

it’s initialization phase has completed as a security measure.

 

-c config-file

Use the rules located in file config-file.

 

-l log-dir

Set the output logging directory to log-dir. All plain text

alerts and packet logs go into this directory. If this option

is not specified, the default logging directory is set to

/var/log/snort.

# service snortd stop

Stopping snort: [ OK ]

 

# service snortd status

snort가 정지되었습니다

 

# cd /var/log/snort

# ls -l

-rw-r--r--. 1 root root 0 2016-06-03 12:52 alert

-rw-------. 1 snort snort 0 2016-06-03 12:54 snort_eth0.pid.lck

 

# chown -R snort:snort /var/log/snort

#

sniffer mode - 네트워크 트래픽을 실시간적으로 분석하는 경우

run-time options:

-v verbose

-d dump package payloads

-x dump entire package in hex

-a display arp packages

-e display link layer data

 

 

TCP/IP packet headers 출력

[TERM2] # ping 168.126.63.1

# snort -v (# snort -v -c /etc/snort/snort.conf -l /var/log/snort)

headers data 부분 출력

# snort -dv (# snort -dv -c /etc/snort/snort.conf -l /var/log/snort)

data link layer headers 출력

# snort -dev (# snort -dev -c /etc/snort/snort.conf -l /var/log/snort)

 

 

log mode - 출력 내용을 로그에 저장

 

command line options

-l dump packages into log directory

-b log packages in binary (tcpdump) format

 

예제

# snort -dev -b -l /var/log/snort -c /etc/snort/snort.conf

# snort -dev -b -l /var/log/snort -h 192.168.20.0/24 -c /etc/snort/snort.conf

 

 

NIDS mode

 

# snort -d -h 192.168.20.0/24 -l /var/log/snort -c /etc/snort/snort.conf -A fast

-A fast : Fast alert mode

-A full

-A unsock

-A none

-A console(screen)

-A cmg(custom mode)

 

[예제]

fast mode

# snort -c /etc/snort/snort.conf -l /var/log/snort -A fast

 

full mode

# snort -c /etc/snort/snort.conf -l /var/log/snort -A full -D

 

checking log files

# ls -l /var/log/snort

# cat alert

# cat snort.log.1389675205

# tcpdump -nr /var/log/snort/snort.log.13897656

 

 

 

barnyard configuration

MySQL configuration

barnyard & snort startup

BASE installation

BASE configuration

 

 

[ snort ---> barnyard2 ---> BASE ---> MySQL ]

 

 

barnyard2 - github.com/firnsy/barnyard2

a dedicated spooler for Snort's unified2 binary output format

an output system for snort, it reads the binary logs from snort using the unified2 format.

It will resend the information of this logs to a database backend

 

 

BASE: Basic Analysis and Security Engine

provides a web front-end to query and analyze the alerts coming from Snort.

The alerts will send to MySQL database, this feature is provided by barnyard2.

http://base.professionallyevil.com/

 

 

 

 

 

Barnyard installation

 

# vi /etc/hosts

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

192.168.20.203 ids.example.com ids

192.168.10.203 nic2

 

# mkdir -p /snort

# cd /snort

# wget --no-check-certificate \

https://github.com/firnsy/barnyard2/archive/master.zip \

-O master.zip

-> 출력내용 생략

 

# unzip master.zip

-> 출력내용 생략

 

# cd barnyard2-master

# ls

autogen.sh COPYING etc m4 README rpm src

configure.ac doc LICENSE Makefile.am RELEASE.NOTES schemas tools

 

(자동) # ./autogen.sh /* update configuration files */

(수동) # autoconf -f -v -i -I ./m4

 

(주의) 선수 패키지 - 아래 패키지가 없는 경우에는 반드시 설치해야 한다.

autogen.sh 스크립트를 실행하기 전에 반드시 확인한다.

(RedHat 계열) # yum -y install autoconf libtool automake

(Debian 계열) # apt-get install autoconf libtool automake

 

# yum -y install autoconf libtool automake

# ./autogen.sh

Found libtoolize

libtoolize: putting auxiliary files in `.'.

libtoolize: copying file `./ltmain.sh'

libtoolize: putting macros in AC_CONFIG_MACRO_DIR, `m4'.

libtoolize: copying file `m4/libtool.m4'

libtoolize: copying file `m4/ltoptions.m4'

libtoolize: copying file `m4/ltsugar.m4'

libtoolize: copying file `m4/ltversion.m4'

libtoolize: copying file `m4/lt~obsolete.m4'

autoreconf: Entering directory `.'

autoreconf: configure.ac: not using Gettext

autoreconf: running: aclocal --force -I m4

autoreconf: configure.ac: tracing

autoreconf: running: libtoolize --copy --force

libtoolize: putting auxiliary files in `.'.

libtoolize: copying file `./ltmain.sh'

libtoolize: putting macros in AC_CONFIG_MACRO_DIR, `m4'.

libtoolize: copying file `m4/libtool.m4'

libtoolize: copying file `m4/ltoptions.m4'

libtoolize: copying file `m4/ltsugar.m4'

libtoolize: copying file `m4/ltversion.m4'

libtoolize: copying file `m4/lt~obsolete.m4'

autoreconf: running: /usr/bin/autoconf --force

autoreconf: running: /usr/bin/autoheader --force

autoreconf: running: automake --add-missing --copy --force-missing

configure.ac:11: installing `./config.guess'

configure.ac:11: installing `./config.sub'

configure.ac:8: installing `./install-sh'

configure.ac:8: installing `./missing'

autoreconf: Leaving directory `.'

You can now run "./configure" and then "make".

 

# ./configure --help | egrep '(mysql|lib)'

--with-mysql=DIR Support for MySQL

--with-mysql-libraries=DIR MySQL library directory

 

# yum -y install mysql mysql-devel

# ln -s /usr/lib64/mysql/libmysqlclient.so.16.0.0 /usr/lib/libmysqlclient.so.16.0.0

# ln -s /usr/lib64/mysql/libmysqlclient_r.so.16.0.0 /usr/lib/libmysqlclient_r.so.16.0.0

 

# cd /snort/barnyard2-master

# ./configure --with-mysql --with-mysql-libraries=/usr/lib64

 

# make

# make install

 

# cp /snort/barnyard2-master/etc/barnyard2.conf /etc/snort

# cp /snort/barnyard2-master/schemas/create_mysql /usr/local/src

 

# mkdir -p /var/log/barnyard2 /* 이전에 디렉토리를 생성했었다. */

# chown -R snort:snort /var/log/barnyard2

 

# cp /snort/snort-*/etc/gen-msg.map /etc/snort

 

barnyard configuration

# vi /etc/snort/barnyard2.conf

[수정전]

227: output alert_fast: stdout

351: #output database: log, mysql, user=root password=test dbname=db host=localhost

[수정후]

227: output alert_fast

351: output database: log, mysql, user=snort password=snort dbname=snort host=localhost

-> 주석 제거 및 수정

 

Setup the MySQL Server

(주의) 반드시 Local에서 작업을 진행한다.

# yum -y install mysql-server

-> 출력 내용 생략

 

# chkconfig mysqld on

# service mysqld start

MySQL 데이타베이스 초기화 중: Installing MySQL system tables...

OK

Filling help tables...

OK

 

To start mysqld at boot time you have to copy

support-files/mysql.server to the right place for your system

 

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !

To do so, start the server, then issue the following commands:

 

/usr/bin/mysqladmin -u root password 'new-password'

/usr/bin/mysqladmin -u root -h ids.example.com password 'new-password'

 

Alternatively you can run:

/usr/bin/mysql_secure_installation

 

which will also give you the option of removing the test

databases and anonymous user created by default. This is

strongly recommended for production servers.

 

See the manual for more instructions.

 

You can start the MySQL daemon with:

cd /usr ; /usr/bin/mysqld_safe &

 

You can test the MySQL daemon with mysql-test-run.pl

cd /usr/mysql-test ; perl mysql-test-run.pl

 

Please report any problems with the /usr/bin/mysqlbug script!

 

[ OK ]

mysqld ()를 시작 중: [ OK ]

 

# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL

SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

 

 

In order to log into MySQL to secure it, we'll need the current

password for the root user. If you've just installed MySQL, and

you haven't set the root password yet, the password will be blank,

so you should just press enter here.

 

Enter current password for root (enter for none): <ENTER>

OK, successfully used password, moving on...

 

Setting the root password ensures that nobody can log into the MySQL

root user without the proper authorisation.

 

Set root password? [Y/n] Y

New password: (soldesk1.)

Re-enter new password: (soldesk1.)

Password updated successfully!

Reloading privilege tables..

... Success!

 

 

By default, a MySQL installation has an anonymous user, allowing anyone

to log into MySQL without having to have a user account created for

them. This is intended only for testing, and to make the installation

go a bit smoother. You should remove them before moving into a

production environment.

 

Remove anonymous users? [Y/n] Y

... Success!

 

Normally, root should only be allowed to connect from 'localhost'. This

ensures that someone cannot guess at the root password from the network.

 

Disallow root login remotely? [Y/n] Y

... Success!

 

By default, MySQL comes with a database named 'test' that anyone can

access. This is also intended only for testing, and should be removed

before moving into a production environment.

 

Remove test database and access to it? [Y/n] Y

- Dropping test database...

... Success!

- Removing privileges on test database...

... Success!

 

Reloading the privilege tables will ensure that all changes made so far

will take effect immediately.

 

Reload privilege tables now? [Y/n] Y

... Success!

 

Cleaning up...

 

 

 

All done! If you've completed all of the above steps, your MySQL

installation should now be secure.

 

Thanks for using MySQL!

 

# mysql -u root -p

Enter password: (soldesk1.)

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 21

Server version: 5.1.73 Source distribution

 

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database snort;

Query OK, 1 row affected (0.00 sec)

 

mysql> grant all on snort.* to snort@localhost;

Query OK, 0 rows affected (0.00 sec)

/* mysql> grant CREATE,INSERT,SELECT,DELETE,UPDATE on snort.* to snort@localhost; */

mysql> set password for snort@localhost=password('snort');

Query OK, 0 rows affected (0.00 sec)

 

mysql> show databases;

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

| Database |

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

| information_schema |

| mysql |

| snort |

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

3 rows in set (0.00 sec)

 

mysql> use snort;

Database changed

mysql> source /usr/local/src/create_mysql <- from barnyard2

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

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 0 rows affected (0.01 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

mysql> show tables;

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

| Tables_in_snort |

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

| data |

| detail |

| encoding |

| event |

| icmphdr |

| iphdr |

| opt |

| reference |

| reference_system |

| schema |

| sensor |

| sig_class |

| sig_reference |

| signature |

| tcphdr |

| udphdr |

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

16 rows in set (0.00 sec)

 

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

 

mysql> exit

 

Start snort using the command

 

(자동) # service snortd restart

(수동) # snort -d -A full -u snort -g snort -c /etc/snort/snort.conf -i eth0 &

 

# service snortd restart

Stopping snort: [실패]

Starting snort: Spawning daemon child...

My daemon child 22470 lives...

Daemon parent exiting (0)

[ OK ]

 

# ls -l /var/log/snort

-> (주의) snort:snort 으로 안되어 있는 파일이 있다면 chown 명령어를 통해 설정을 바꿔야 한다.

# chown -R snort:snort /var/log/snort

 

[TERM2] 다른 터미널에서 수행

# barnyard2 -c /etc/snort/barnyard2.conf \

-d /var/log/snort -f snort.log \

-w /etc/snort/bylog.waldo \

-C /etc/snort/classification.config

Running in Continuous mode

 

--== Initializing Barnyard2 ==--

Initializing Input Plugins!

Initializing Output Plugins!

Parsing config file "/etc/snort/barnyard2.conf"

 

 

+[ Signature Suppress list ]+

----------------------------

+[No entry in Signature Suppress List]+

----------------------------

+[ Signature Suppress list ]+

 

Barnyard2 spooler: Event cache size set to [2048]

Log directory = /var/log/barnyard2

INFO database: Defaulting Reconnect/Transaction Error limit to 10

INFO database: Defaulting Reconnect sleep time to 5 second

[ClassificationPullDataStore()]: No Classification found in database ...

[SignaturePullDataStore()]: No signature found in database ...

[SystemPullDataStore()]: No System found in database ...

[ReferencePullDataStore()]: No Reference found in database ...

[SignatureReferencePullDataStore()]: No Reference found in database ...

database: compiled support for (mysql)

database: configured to use mysql

database: schema version = 107

database: host = localhost

database: user = snort

database: database name = snort

database: sensor name = ids.example.com:NULL

database: sensor id = 1

database: sensor cid = 1

database: data encoding = hex

database: detail level = full

database: ignore_bpf = no

database: using the "log" facility

 

--== Initialization Complete ==--

 

______ -*> Barnyard2 <*-

/ ,,_ \ Version 2.1.14 (Build 337)

|o" )~| By Ian Firns (SecurixLive): http://www.securixlive.com/

+ '''' + (C) Copyright 2008-2013 Ian Firns <firnsy@securixlive.com>

 

WARNING: Unable to open waldo file '/etc/snort/bylog.waldo' (No such file or directory)

Opened spool file '/var/log/snort/snort.log.1464866678'

Closing spool file '/var/log/snort/snort.log.1464866678'. Read 0 records

Opened spool file '/var/log/snort/snort.log.1464866810'

Closing spool file '/var/log/snort/snort.log.1464866810'. Read 0 records

Opened spool file '/var/log/snort/snort.log.1464870215'

Waiting for new data

 

-> 약간 실행 시간이 걸리기 때문에 기다린다.

-> 5~ 10분정도

 

check mysql

# mysql -u root -p

Enter password: (soldesk1.)

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 12

Server version: 5.1.73 Source distribution

 

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> use snort;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed

mysql> select count(*) from event;

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

| count(*) |

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

| 0 | <---- barnyard2 프로그램이 /var/log/snort/<snort log> 파일을 읽어 들

+----------+ event count가 늘어난다.

1 row in set (0.00 sec)

 

mysql> exit

 

 

[참고]

https://www.youtube.com/watch?v=II80tzwEuFk

 

 

 

 

 

BASE Installation

Prerequisite program installation

# yum install libxml2 \

php \

php-gd \

php-cli \

php-mysql \

php-pear \

php-pear-Log \

php-dba \

php-dbase \

php-odbc \

php-pear-Image-Graph

 

php editing - BASE Log level

# vi /etc/php.ini

[수정전]

513: error_reporting = E_ALL & ~E_DEPRECATED

[수정후]

513: error_reporting = E_ALL & ~E_NOTICE

-> 내용 수정

 

# service httpd restart

httpd 를 정지 중: [실패]

httpd ()를 시작 중: [ OK ]

 

# tail -f /var/log/httpd/error_log

-> 에러 메세지를 확인하고 적당한 설정을 변경한다.

-> <CTRL + C> 끊는다.

 

BASE and Adodb download

# cd /snort

# wget --no-check-certificate \

http://sourceforge.net/projects/secureideas/files/BASE/base-1.4.5/base-1.4.5.tar.gz

-> 출력 내용 생략

 

# tar xvzf base-1.4.5.tar.gz

-> 출력 내용 생략

 

# cp -r base-1.4.5 /var/www/html/base

# chown -R apache:apache /var/www/html/base

# chmod 777 /var/www/html/base

 

Adodb(a database abstraction library for PHP)

download http://sourceforge.net/projects/adodb/

# cd /snort

# wget --no-check-certificate http://sourceforge.net/projects/adodb/files/latest/download

-> 출력 내용 생략

 

# tar xvzf adodb-*.tar.gz

-> 출력 내용 생략

 

# mkdir /var/www/lib

# cp -r adodb5 /var/www/lib

 


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160803 소프트웨어 관리  (0) 2016.08.03
20160802 웹 방화벽  (0) 2016.08.02
20160801 IDS  (0) 2016.08.01
20160801 TCP Wrapper  (0) 2016.08.01
20160801 NTP  (0) 2016.08.01
Posted by 22Hz
, |

 

 

 

CentOS 6.X 설치 및 설정 작업

 

 

 

0. 설치 전 준비 사항

CentOS 6.X(EX: CentOS 6.4 or CentOS 6.5) CD/DVD 준비

VMware NAT Device쪽에 DHCP 서버가 켜져 있는지 확인

 

 

1. 설치 계획

네트워크 설정 정보

--------------------------------------

hostname : ids.example.com

IP1(eth0) : 192.168.20.203/24

IP2(eth1) : 192.168.10.203/24

Gateway : 192.168.10.2

DNS : 168.126.63.1

--------------------------------------

root 사용자 암호: soldesk1.

 

 

2. 설치 과정

Welcome to CentOS 6.4! 화면-> Install or upgrade an existing system

Disc Found 화면-> Skip

CentOS 6 화면-> Next

Language 선택 화면-> Korean -> Next

키보드 선택 화면-> U.S. 영어 -> Next

설치 장치 선택 화면-> 기본 저장 장치 -> Next -> 저장 장치 경고 -> , 모든 데이터를 삭제합니다.

호스트 이름 설정 화면-> ids.example.com -> Next

시간대(타임존) 선택-> 아시아/서울 -> Next

root 사용자 암호 설정-> soldesk1. -> Next

설치 타입 선택 화면-> 모든 공간 사용 -> Next

패키지 그룹(소프트웨어 그룹) 선택-> Desktop -> Next

재부팅

환영합니다. 화면-> Next

라이센스 정보 화면-> , 라이센스 조항에 동의합니다. -> Next

사용자 생성 화면-> ID/PASS: snort/snort -> Next

날짜 및 시간 화면-> Next

Kdump 화면-> Finish

 

 

3. 설치 후 작업

화면 해상도 조정

시스템 > 기본설정 > 디스플레이

폰트 조정

시스템 > 기본설정 > 모양새 > 글꼴

VMware Tools 설치

VMware > VM > Install VMware tools

# ./vmware-install.pl -default

# init 3 ; init 5

4. 설치후 네트워크 설정 과정

 

자동 설정 방식(EX: NetworkManager)

수동 설정 방식(EX: 직접 작업하는 경우)

 

 

수동 설정 방식

 

(ids.example.com) 192.168.20.203

 

네트워크가 되는지 확인하기 위해서 오른쪽 상단의 네트워크 아이콘을 선택하고

 

"system eth0" 선택하여 DHCP 서버로 부터 정상적으로 IP를 할당 받는지 확인한다.

 

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:45:A1:D8

inet addr:192.168.10.156 Bcast:192.168.10.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1d8/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:354 errors:0 dropped:0 overruns:0 frame:0

TX packets:154 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:66887 (65.3 KiB) TX bytes:12334 (12.0 KiB)

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:24 errors:0 dropped:0 overruns:0 frame:0

TX packets:24 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:1440 (1.4 KiB) TX bytes:1440 (1.4 KiB)

 

# setup

=> Network configuration

=> Device configuration

=> eth0 (eth0) - Intel Corporation 82545EM Gigabit Ethernet Controller (Copper)

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

| Name eth0

| Device eth0

| Use DHCP [ ]

| Static IP 192.168.20.203

| Netmask 255.255.255.0

| Default gateway IP ____________

| Primary DNS Server 168.126.63.1

| Secondary DNS Server ____________

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

 

=> DNS configuration

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

| Hostname ids.example.com

| Primary DNS _______________

| Secondary DNS _______________

| Tertiary DNS _______________

| DNS search path example.com

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

 

 

 

 

 

(주의) "# service network restart" 사용하지 않는다.

 

# chkconfig NetworkManager off

# service NetworkManager stop

 

# cat /etc/sysconfig/network

NETWORKING=yes

HOSTNAME=ids.example.com

 

# vi /etc/sysconfig/network-scripts/ifcfg-eth0

[수정전]

DEVICE=eth0

HWADDR=00:0c:29:45:a1:d8

TYPE=Ethernet

UUID=93a183c1-808e-41b1-8749-4c6da12fba98

ONBOOT=no

NM_CONTROLLED=yes

BOOTPROTO=none

IPADDR=192.168.20.203

NETMASK=255.255.255.0

IPV6INIT=no

USERCTL=no

DNS1=168.126.63.1

[수정후]

DEVICE=eth0

HWADDR=00:0c:29:45:a1:d8

TYPE=Ethernet

UUID=93a183c1-808e-41b1-8749-4c6da12fba98

ONBOOT=yes

NM_CONTROLLED=no

BOOTPROTO=none

IPADDR=192.168.20.203

NETMASK=255.255.255.0

IPV6INIT=no

USERCTL=no

DNS1=168.126.63.1

 

# ifdown eth0

# ifup eth0

 

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:45:A1:D8

inet addr:192.168.20.203 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1d8/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:11839 errors:0 dropped:0 overruns:0 frame:0

TX packets:6490 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:17348047 (16.5 MiB) TX bytes:356695 (348.3 KiB)

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:32 errors:0 dropped:0 overruns:0 frame:0

TX packets:32 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:2066 (2.0 KiB) TX bytes:2066 (2.0 KiB)

 

# route -n (# netstat -nr)

Kernel IP routing table

Destination Gateway Genmask Flags MSS Window irtt Iface

192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0

 

 

3. 새로운 Network Adapter(eth1) 추가 및 네트워크 설정

 

# poweroff (# halt, # init 0, # shutdown -h now)

 

VMware > VM > Settings > Add > Network Adapter > NAT

 

서버 Power ON

 

root 사용자로 로그인

 

# cd /etc/sysconfig/network-scripts

# ls

ifcfg-eth0 ifdown-isdn ifup-aliases ifup-plusb init.ipv6-global

ifcfg-lo ifdown-post ifup-bnep ifup-post net.hotplug

ifdown ifdown-ppp ifup-eth ifup-ppp network-functions

ifdown-bnep ifdown-routes ifup-ippp ifup-routes network-functions-ipv6

ifdown-eth ifdown-sit ifup-ipv6 ifup-sit

ifdown-ippp ifdown-tunnel ifup-isdn ifup-tunnel

ifdown-ipv6 ifup ifup-plip ifup-wireless

-> ifcfg-eth1 파일 존재하는가?

 

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:6A:47:8C

inet addr:192.168.20.203 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe6a:478c/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:10 errors:0 dropped:0 overruns:0 frame:0

TX packets:6 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:1577 (1.5 KiB) TX bytes:468 (468.0 b)

 

eth1 Link encap:Ethernet HWaddr 00:0C:29:6A:47:96

inet addr:192.168.10.162 Bcast:192.168.10.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe6a:4796/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:24 errors:0 dropped:0 overruns:0 frame:0

TX packets:24 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:11067 (10.8 KiB) TX bytes:2220 (2.1 KiB)

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:16 errors:0 dropped:0 overruns:0 frame:0

TX packets:16 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:960 (960.0 b) TX bytes:960 (960.0 b)

-> eth1 보이는가? 설정이 존재하는가?

 

# setup

=> Network configuration

=> Device configuration

=> <New Device>

=> Ethernet

--------------------------------------------

Name eth1

Device eth1

Use DHCP [ ]

Static IP 192.168.10.203

Netmask 255.255.255.0

Default gateway IP 192.168.10.2

Primary DNS Server 168.126.63.1

Secondary DNS Server ____________________

--------------------------------------------

 

 

 

 

# cd /etc/sysconfig/network-scripts

# ls

ifcfg-eth0 ifdown-ipv6 ifup ifup-plip ifup-wireless

ifcfg-eth1 ifdown-isdn ifup-aliases ifup-plusb init.ipv6-global

ifcfg-lo ifdown-post ifup-bnep ifup-post net.hotplug

ifdown ifdown-ppp ifup-eth ifup-ppp network-functions

ifdown-bnep ifdown-routes ifup-ippp ifup-routes network-functions-ipv6

ifdown-eth ifdown-sit ifup-ipv6 ifup-sit

ifdown-ippp ifdown-tunnel ifup-isdn ifup-tunnel

 

(주의) "# service network restart" 사용하지 않는다.

 

# ifdown eth1

# ifup eth1

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:45:A1:D8

inet addr:192.168.20.203 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1d8/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:114 errors:0 dropped:0 overruns:0 frame:0

TX packets:6 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:11539 (11.2 KiB) TX bytes:468 (468.0 b)

 

eth1 Link encap:Ethernet HWaddr 00:0C:29:45:A1:E2

inet addr:192.168.10.203 Bcast:192.168.10.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fe45:a1e2/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:131 errors:0 dropped:0 overruns:0 frame:0

TX packets:28 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:21796 (21.2 KiB) TX bytes:2945 (2.8 KiB)

..... (생략) .....

 

# route -n (# netstat -nr)

Kernel IP routing table

Destination Gateway Genmask Flags Metric Ref Use Iface

192.168.20.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0

192.168.10.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1

169.254.0.0 0.0.0.0 255.255.0.0 U 1002 0 0 eth0

169.254.0.0 0.0.0.0 255.255.0.0 U 1003 0 0 eth1

0.0.0.0 192.168.10.2 0.0.0.0 UG 0 0 0 eth1

 

 

 

4. 기타 작업

 

방화벽 끄기

# iptables -F

# iptables -F -t nat

# rm -f /etc/sysconfig/iptables

SELinux 끄기

# vi /etc/sysconfig/selinux

# reboot

 

방화벽 끄기

# iptables -L

Chain INPUT (policy ACCEPT)

target prot opt source destination

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT icmp -- anywhere anywhere

ACCEPT all -- anywhere anywhere

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh

REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

# iptables -L -t nat

Chain PREROUTING (policy ACCEPT)

target prot opt source destination

 

Chain POSTROUTING (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

# cat /etc/sysconfig/iptables

# Firewall configuration written by system-config-firewall

# Manual customization of this file is not recommended.

*filter

:INPUT ACCEPT [0:0]

:FORWARD ACCEPT [0:0]

:OUTPUT ACCEPT [0:0]

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

-A INPUT -p icmp -j ACCEPT

-A INPUT -i lo -j ACCEPT

-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

-A INPUT -j REJECT --reject-with icmp-host-prohibited

-A FORWARD -j REJECT --reject-with icmp-host-prohibited

COMMIT

 

# chkconfig --list iptables

iptables 0:해제 1:해제 2:활성 3:활성 4:활성 5:활성 6:해제

 

# iptables -F

# iptables -F -t nat

 

# rm -f /etc/sysconfig/iptables

 

 

 

 

SELinux 끄기

 

# getenforce (# sestatus)

Enforcing

 

# vi /etc/sysconfig/selinux

# This file controls the state of SELinux on the system.

# SELINUX= can take one of these three values:

# enforcing - SELinux security policy is enforced.

# permissive - SELinux prints warnings instead of enforcing.

# disabled - No SELinux policy is loaded.

[수정전]

SELINUX=enforcing

[수정후]

SELINUX=disabled

# SELINUXTYPE= can take one of these two values:

# targeted - Targeted processes are protected,

# mls - Multi Level Security protection.

SELINUXTYPE=targeted

 

# reboot

 

재부팅이 된 이후에 root 사용자로 로그인하여 SELinux Mode 확인

 

# getenforce (# sestatus)

Disabled

 

 

 

 

 

 

 

 

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160802 웹 방화벽  (0) 2016.08.02
20160802 Snort  (0) 2016.08.02
20160801 TCP Wrapper  (0) 2016.08.01
20160801 NTP  (0) 2016.08.01
20160729 방화벽  (0) 2016.07.29
Posted by 22Hz
, |

 

 

 

 

 

 

접근 제어(Access Control)

- 호스트/네트워크 접근 제어 ---> 방화벽(iptables), tcp_wrapper, 각 서비스 설정

- 사용자 접근 제어 ---> 각 서비스 설정

-> 호스트/네트워크 접근 제어 + 사용자 접근 제어

 

 

 

 

 

 

 

[참고] tcp_wrappers & iptables

tcp_wrappers

(장점) 설정이 간단함(쉽게 설정 가능), 성능 저하 거의 없음.

(단점) 모든 서비스에 대한 제어가 가능하지 않음.

iptables(Firewall)

(장점) 모든 서비스에 대한 제어가 가능.

(단점) 설정이 복작함. 성능 저하가 발생.

 




 

1

접근 제어(Access Control)

 

(1) 서비스를 on/off 시킬수 있는 툴은 다음과 같다.

 

Service Configuration Tool(system-config-services, serviceconf)A graphical application that displays a description of each service, displays whether each service is started at boot time (for runlevels 3, 4, and 5), and allows services to be started, stopped, and restarted.# system-config-services & or# serviceconf &

ntsysv(ntsysv, setup)A text-based application that allows you to configure which services are started at boot time for each runlevel. Non-xinetd services can not be started, stopped, or restarted using this program.# ntsysv or# setup

chkconfigA command line utility that allows you to turn services on and off for the different runlevels. Non-xinetd services can not be started, stopped, or restarted using this utility.# chkconfig --list (standalone) # chkconfig named on/off ---> /etc/rc#.d/S##script(xinetd ) # chkconfig krb5-telnet on/off ---> /etc/xinetd.d/krb5-telnet

/etc/init.d/script(/etc/rc.d/init.d/script)# service xinetd restart = /etc/init.d/xinetd restart /etc/rc.d/init.d/xinetd restart(standalone) # chkconfig named on ; service named restart(xinetd ) # chkconfig krb5-telnet on ; service xinetd restart

 

-> 불필요한 서비스 목록 점검

-> 불필요한 서비스 off(disable)

 

() 웹서버라면?

-> 필요한 서비스

() WAS 서버(80,8080,443))

() FTP(21,20)/SFTP(22)

() TELNET(23)/SSH(22))

() NTP(123)

() ping, traceroute CMD

(2) 서비스를 접근 제어(Service Access Control)할 수 있는 툴

 

iptablesAnother way to manage access to system services is by using iptables to configure an IP firewall. If you are a new Linux user, please realize that iptables may not be the best solution for you. Setting up iptables can be complicated and is best tackled by experienced Linux system administrators. On the other hand, the benefit of using iptables is flexibility. For example, if you need a customized solution which provides certain hosts access to certain services, iptables can provide it for you.# iptables -L

Security Level Configuration(system-config-securitylevel)if you are looking for a utility to set general access rules for your home machine, and/or if you are new to Linux, try the Security Level Configuration Tool (system-configsecuritylevel), which allows you to select the security level for your system, similar to the Firewall Configuration screen in the installation program.# system-config-securitylevel &

lokkit(lokkit, system-config-securitylevel-tui)A text-based application# lokkit (# system-config-securitylevel-tui)

 

 


 

[그림] 호스트 및 사용자 제한

 

 


(3) 보안에 관련한 관리자의 정책

 

최소 권한

모든 서비스에 대해서 특별하게 서비스를 열어야 허용해야할지 차단해야할지 모든다면 기본적으로 차단한다.


중앙집중적인 관리

보안적인 관리를 하기 위해서는 여러개의 툴을 통해 관리하는 것 보다 중앙집중적인 툴을 통해 관리하는 것이 좋다.


로그 기록 확인

정기적으로 보안적인 로그 파일을 점검하고 관리한다.

- /var/log/messages

- /var/log/secure

- /var/log/lastlog

- 기타


최신의 보안이슈

최신의 보안이슈에 대해 점검하기 위해서 메일링 리스트에 가입해 놓고 정기적으로 확인한다.

- redhat-watch (http://www.redhat.com/mailman/listinfo/redhat-watch-list)

- BUGTRAQ (http://www.securityfocus.com/forums/bugtraq/)

- CERT (http://www.cert.org)

- SANS (http://www.sans.org)


프로그램(패키지) 업데이트

정기적으로 버그가 있는 패키지를 업그레이드 한다.

(주의) 프로그램 업데이트가 개발자에 의해 개발된 소스와 연동하는 경우의 업그레이드는 주의하여야 한다.

- up2date(up2date --configure)

- yum -y update (yum -y update PKG)

 

 

 

 

 

2

TCP_Wrapper

 

 

리눅스에서 TCP Wrapper 여러가지 서비스들의 접근을 제어한다. 시스템에 접근을 허락할 호스트와 접근을 차단할 호스트를 정의할 수 있는 프로그램이다. TCP Wrapper 프로그램은 tcpd 데몬을 사용하고 있다.

 

다음은 tcp_wrapper의 동작 원리를 나타낸다.


 

 

 

(1) tcpd 데몬

 

# man tcpd

The tcpd program can be set up to monitor incoming requests for telnet, finger,

ftp, exec, rsh, rlogin, tftp, talk, comsat and other services that have a one-

to-one mapping onto executable files.

 

The program supports both 4.3BSD-style sockets and System V.4-style TLI. Func-

tionality may be limited when the protocol underneath TLI is not an internet

protocol.

 

Operation is as follows: whenever a request for service arrives, the inetd dae-

mon is tricked into running the tcpd program instead of the desired server. tcpd

logs the request and does some additional checks. When all is well, tcpd runs

the appropriate server program and goes away.

 

Optional features are: pattern-based access control, client username lookups

with the RFC 931 etc. protocol, protection against hosts that pretend to have

someone elses host name, and protection against hosts that pretend to have some-

one elses network address.

 

 

 

(2) /etc/hosts.allow, /etc/hosts.deny 파일

 

This manual page describes a simple access control language that is based on

client (host name/address, user name), and server (process name, host

name/address) patterns. Examples are given at the end. The impatient reader is

encouraged to skip to the EXAMPLES section for a quick introduction.

 

An extended version of the access control language is described in the

hosts_options(5) document. The extensions are turned on at program build time by

building with -DPROCESS_OPTIONS.

 

In the following text, daemon is the the process name of a network daemon pro-

cess, and client is the name and/or address of a host requesting service. Net-

work daemon process names are specified in the inetd configuration file.

 

The access control software consults two files. The search stops at the first

match:

 

· Access will be granted when a (daemon,client) pair matches an entry in

the /etc/hosts.allow file.

 

· Otherwise, access will be denied when a (daemon,client) pair matches an

entry in the /etc/hosts.deny file.

 

· Otherwise, access will be granted.

 

A non-existing access control file is treated as if it were an empty file. Thus,

access control can be turned off by providing no access control files.

 

 

 

 

 

(3) TCP Wrappers

 

tcp_wrapper (/usr/share/doc/tcp_wrappers-7.6)

tcp_wrapperfinger, ftp, telnet, rlogin, rsh, exec, tftp, talk, comsat등의 네트워크 서비스를 필터링 할 수 있는 프로그램이다.

/usr/sbin/tcpd 데몬에 의해서 TCP 서비스를 제어 하는 역할을 가지고 있다.

TCP 제어를 위해서는 /etc/hosts.allow, /etc/hosts.deny 파일을 가지고 설정한다.

(Rule 적용 순서)

- /etc/hosts.allow 파일에 정의된것은 허용이 되고,

- 만약 정의 되지 않은 내용이 있다면, /etc/hosts.deny 파일에 정의된것은 거부가 되고,

- 만약 정의 되지 않은 내용이 있다면, 허용된다.

------> tcpd ---+----> /etc/hosts.allow(Allow)

                |

                +----------------------------> /etc/hosts.deny(Deny)

                |

                +--------------------------------------------------> (Allow)

 


tcp_wrapperFirewall(iptable)과 비교하였을때 성능을 떨어트리지 않는 장점을 가지고 있다. 빠르게 tcp 방식의 서비스를 제어할 수 있는 장점을 가지고 있다. 하지만 Firewall(iptable) 처럼 모든 서비스를 제어하지는 못한다. sshd, xinetd, portmap 데몬을 관리한다. tcp_wrapper를 사용하여 제어할 수 있는 데몬들은 libwrap(동적 라이브러리)을 사용하고 있다.

(권장) 이 파일에 설정할 때 시스템이름이나 도메인 이름을 사용하지 말고 IP주소를 사용할 것을 권장합니다.

(권장) 또한, /etc/hosts.deny 파일에는 deny ALL로 설정한 후 접속을 허용할 주소만 /etc/hosts.allow 파일에 기록할것을 권장한다.

(주의) 2개의 설정파일(/etc/hosts.allow, /etc/hosts.deny)에 정의를 할 때 저장하는 즉시 유효하므로 작성시에 주의하여야 합니다. (서비스를 restart 하는 방법이 아니므로 주의해야 한다.)

(주의) 서비스 차단시 portmap(111) 서비스는 다른 서비스들(EX: NFS, NIS)과 상관이 있으므로 주의해서 차단할 것을 권장한다.

2(EX: /etc/hosts.allow, /etc/hosts.deny)의 설정 파일에 정의하는 방식은 다음과 같습니다.<데몬이름>: <Source IP주소 or 네트워크 or 이름>::[옵션]

 

 

 

(4) 접근 제어 규칙

 

/etc/hosts.allow, /etc/hosts.deny 파일을 가지고 접근 제어를 할수 있다.

 

 

() 파일 작성시 문법 규칙

 

새로운 줄(줄바꿈)은 무시되고, 줄을 연장할 경우에는 백슬래쉬를 사용해야 한다.

빈줄 혹은 ‘#’으로 시작되는 줄은 주석처리이다.

다른 모든 줄은 아래의 형식을 따라야 한다.

() daemon_list : client_list [ : shell_command ]

daemon_list : 한 개 이상의 데몬(서버 프로그램) 프로세스 혹은 예약어(와일드 카드)

client_list : 한 개 이상의 호스트 이름, 주소, 패턴 혹은 예약어(클라이언트 이름 혹은 주소가 일치하는 것) (IP 주소 지정 예 ) 192.168.0.1, 10.0.0. (이름으로 지정 예 ) www.redhat.com, .example.com (넷마스크로 지정 예) 192.168.0.0/255.255.255.0 (네트워크 이름으로 지정 예) @mynetwork (/etc/networks or NIS 네트워크 이름)

 

 

() 예약어(와일드 카드)

 

ALL : 모든 서비스 또는 모든 호스트를 나타냄

LOCAL : 같은 네트워크에 있는 모든 호스트

KNOWN : 이름이 KNOWN 호스트, 혹은 이름 또는 주소를 알고 있는 호스트

UNKNOWN : 이름이 UNKNWON 호스트, 혹은 이름이나 주소를 모르는 호스트

PARANOID : 호스트이름이 주소와 일치되지 않는 호스트(정방향/역방향 검색이 일치하지 않는 모든 호스트)

B EXCEPT A : 목록 B에서 A를 제외한 모든 B

 

 

 

 

() 패턴형식

 

':'의 위치에 유념해야 하고, ALL':'은 공백이 있어야 한다.

 

# cat /etc/hosts.allow

vsftpd: LOCAL 192.168.0.140

-> vsftpd: vsftpd 데몬에 대해서

-> LOCAL 자신의 IP

-> 192.168.0.240 허용할 IP

 

# cat /etc/hosts.deny

vsftpd: ALL

-> vsftpd: vsftpd 데몬에 대해서

-> ALL 모든 지역의 IP 차단

 

 

 

() Shell Command

 

명령

spawn : 현재 수행중인 프로세스의 자식프로세스(Child Process)로 수행

twist : 현재 수행중인 프로세스의 이미지 교체 후 수행 (프로세스의 이미지가 교체되므로 규칙의 마지막 옵션으로 사용해야 한다.


확장 옵션

%a (%A): 클라이언트(서버)의 주소

%c : 클라이언트의 정보(EX: user01@example.com)

%n (%N): 클라이언트의 이름

%d : 서비스 데몬의 이름

%h (%H): 클라이언트(서버) 이름 또는 주소

%p : 데몬 프로세스 ID

%s : 서버 정보

%u : 클라이언트 사용자 이름

 

사용예

의심되는 호스트(cracker.example.com)가 시스템에 접근을 시도할 경우 접속을 거부하고 관리자에게 관련 정보를 전송하기 위해서 hosts.deny 파일에 다음과 같이 설정한다.

# cat /etc/hosts.denyALL: cracker.example.com: twist (finger -l @%h | mail -s %d -%h root) &

 

 

 

 

(tcp_wrappers을 사용하는 예) /etc/hosts.allow 파일에 정의한 예라고 생각한다.

ALL: localhost .yahoo.com

localhostyahoo.com 도메인 이름을 가진 모든 호스트에게 서비스를 허용한다.

 

ALL: *.example.com

example.com 도메인의 모든 호스트를 허용한다.

 

vsftpd: 192.168.0.2 192.168.0.3 192.168.1. 172.16.

192.168.0.2, 192.168.0.3, 192.168.1.0, 172.16.0.0 호스트/네트워크에 대한 서비스를 허용한다.

 

ALL: .daum.net EXCEPT killer.daum.net

daum.net 도메인 중 killer.daum.net 호스트를 제외한 모든 호스트에 대한 서비스를 허용한다.

 

ALL EXCEPT vsftpd: .paran.com EXCEPT cafe.paran.com

vsftpd 데몬을 제외한 모든 서비스들에 대해 cafe.paran.com 호스트를 제외한 모든 paran.com 호스트를 허용한다.

 

ALL: ALL: DENY

모든 서비스(데몬)에 대해 모든 호스트들의 서비스는 거부된다.

 

ALL: 192.168.0.0/24 192.168.1.0/255.255.255.0

모든 서비스를 192.168.0.0/24, 192.168.1.0/24 네트워크들에 대해서 서비스를 허용한다.

`

sshd: .example.com : severity emerg

SSH 서비스에 대해서 .example.com 도메인으로 들어 오는 모든 서비스를 로그 기록을 생성한다. 대신 로그 레벨을 emerg(emergency)로 생성한다.

이런 경우 /etc/syslog.conf 파일에 정의가 되어 있어야 한다.

 

sshd: .example.com : severity local0.alert

SSH 서비스에 대해서 .example.com 도메인으로 들어 오는 모든 서비스를 로그 기록을 생성한다. 대신 로그 레벨을 local0.alert로 생성한다.

이런 경우 /etc/syslog.conf 파일에 정의가 되어 있어야 한다.

 

in.telnetd: /etc/telnet.hosts

TELNET 서비스에 대해서 /etc/telnet.hosts 파일에 정의된 대역 또는 호스트들을 허용한다.

 

sshd: .example.com: spawn /bin/echo `/bin/date` access denied >> /var/log/sshd.log : DENY

SSH 서비스에 대해서 .example.com 도메인으로 접근하는 서비스들은 거부하고 /var/log/sshd.log 파일에 기록으로 남긴다.

 

in.telnetd: .example.com : spawn /bin/echo `/bin/date` from %h >> /var/log/telnet.log : ALLOW

TELNET 서비스에 대해서 .example.com 도메인으로 들어오는 서비스를 허략하고 /var/log/telnet.log 파일에 기록으로 남긴다.

 

vsftpd: .example.com : twist /bin/echo "421 Bad hacker, go away!"

FTP 서비스에 대해서 .example.com 도메인으로 접근하는 서비스들은 특별한 메세지를 출력한다.

 

sshd: client1.example.com : ALLOW sshd : client2.example.com : DENY

SSH 서비스에 대해서 client1.example.com에서 들어 오는 접근은 허용하고 client2.example.com으로 접근하는 서비스는 거부한다.

 

 

 

 

 

3

TCP_Wrapper 실습

 

 

TCP Wrapper에 대해서 실습하여 보자.

 

 

[EX1] TCP Wrapper 기본적인 확인

 

 

패키지: tcp_wrapper

(192.168.20.200) (192.168.20.50)

----- HostA ----- ----- HostB -----

 

# vi /etc/hosts.deny <----------------------- # ssh 192.168.20.200

sshd : .example.com : spawn /bin/echo `/bin/date` \ access denied >> /var/log/sshd.log : deny

----------------- -----------------

 

 

 

(192.168.20.200) linux200

 

다음과 같은 서비스가 가능한 상태라고 가정한다.

telnet 서비스 (# chkconfig krb5-telnet on ; service xinetd restart ; telnet localhost)

sshd 서비스 (# chkconfig sshd on ; service sshd restart ; ssh localhost)

vsftpd 서비스 (# chkconfig vsftpd on ; service vsftpd restart ; ftp localhost)

 

서버에서는 기본적으로 /var/log/messages, /var/log/secure 파일을 모니터링 하고 있다고 가정한다.

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

 

 

tcp_wrapper 패키지 확인

# rpm -qa | grep tcp_wrappers

tcp_wrappers-7.6-40.7.el5

 

---------------------------------------------------------

RedHat 계열) # rpm -qa (# rpm -qa | grep ssh)

# rpm -ql <PKG>

# rpm -qf /etc/passwd

---------------------------------------------------------

Debian 계열) # dpkg -l (# dpkg -l | grep ssh)

# dpkg -L <PKG>

# dpkg -S /etc/passwd

---------------------------------------------------------

 

# rpm -ql tcp_wrappers

/lib/libwrap.so.0

/lib/libwrap.so.0.7.6

/usr/include/tcpd.h

/usr/lib/libwrap.a

/usr/lib/libwrap.so

/usr/sbin/safe_finger

/usr/sbin/tcpd

/usr/sbin/try-from

/usr/share/doc/tcp_wrappers-7.6

/usr/share/doc/tcp_wrappers-7.6/BLURB

/usr/share/doc/tcp_wrappers-7.6/Banners.Makefile

/usr/share/doc/tcp_wrappers-7.6/CHANGES

/usr/share/doc/tcp_wrappers-7.6/DISCLAIMER

/usr/share/doc/tcp_wrappers-7.6/README

/usr/share/doc/tcp_wrappers-7.6/README.IRIX

/usr/share/doc/tcp_wrappers-7.6/README.NIS

/usr/share/man/man3/hosts_access.3.gz

/usr/share/man/man5/hosts.allow.5.gz

/usr/share/man/man5/hosts.deny.5.gz

/usr/share/man/man5/hosts_access.5.gz

/usr/share/man/man5/hosts_options.5.gz

/usr/share/man/man8/tcpd.8.gz

 

(필요하면 명령어 수행) tcpd 데몬에 의해서 제어 되는 서비스 확인 방법

# which xinetd -> /usr/sbin/xinetd

# ldd /usr/sbin/xinetd | grep libwrap (0)

# strings /usr/sbin/xinetd | grep hosts

 

# which vsftpd -> /usr/sbin/vsftpd

# ldd /usr/sbin/vsftpd | grep libwrap (0)

# strings /usr/sbin/vsftpd | grep hosts

 

# which httpd -> /usr/sbin/httpd

# ldd /usr/sbin/httpd | grep libwrap (X)

# strings /usr/sbin/httpd | grep hosts

 

/etc/hosts.allow, /etc/hosts.deny 파일 확인

# ls /etc/hosts.*

/etc/hosts.allow /etc/hosts.deny

# cat /etc/hosts.allow

#

# hosts.allow This file describes the names of the hosts which are

# allowed to use the local INET services, as decided

# by the '/usr/sbin/tcpd' server.

#

 

# cat /etc/hosts.deny

#

# hosts.deny This file describes the names of the hosts which are

# *not* allowed to use the local INET services, as decided

# by the '/usr/sbin/tcpd' server.

#

# The portmap line is redundant, but it is left to remind you that

# the new secure portmap uses hosts.deny and hosts.allow. In particular

# you should know that NFS uses portmap!

 

/etc/hosts.deny 파일에 모든 서비스 거절 등록 및 확인

# vi /etc/hosts.deny

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

#

# All Service Denied

#

ALL: ALL

-> /etc/hosts.deny, /etc/hosts.allow 파일에 정의하자마자 적용되는것이기 때문에 정의할 때 주의해야 한다.

 

# telnet localhost

Trying 127.0.0.1...

Connected to localhost.localdomain (127.0.0.1).

Escape character is '^]'.

Connection closed by foreign host.

# ssh localhost

ssh_exchange_identification: Connection closed by remote host

-> 약간 시간이 걸린다.(3 ~ 5)

 

# ftp localhost

Connected to linux2XX.com.

421 Service not available.

ftp> quit

 

 

 

(192.168.20.50) KaliLinux

 

# telnet 192.168.20.200

Trying 192.168.20.200...

Connected to 192.168.20.200 (192.168.20.200).

Escape character is '^]'.

Connection closed by foreign host.

 

# ssh 192.168.20.200

ssh_exchange_identification: Connection closed by remote host

# ftp 192.168.20.200

Connected to 192.168.20.200.

421 Service not available.

ftp> quit

 

 

 

(192.168.20.200) linux200

 

# vi /etc/hosts.allow

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

#

# Allow Policy

#

ALL: 127. 192.168.20.200

-> 192.168.20.200 (자신의 IP)

 

# telnet localhost

# ssh localhost

# ftp localhost

 

# which nmap

# yum -y install nmap

# nmap 192.168.20.200

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-10 15:34 KST

Interesting ports on linux200.example.com (192.168.20.200):

Not shown: 1666 closed ports

PORT STATE SERVICE

21/tcp open ftp

22/tcp open ssh

23/tcp open telnet

25/tcp open smtp

37/tcp open time

53/tcp open domain

80/tcp open http

110/tcp open pop3

111/tcp open rpcbind

143/tcp open imap

443/tcp open https

864/tcp open unknown

993/tcp open imaps

995/tcp open pop3s

 

Nmap finished: 1 IP address (1 host up) scanned in 0.122 seconds

 

# vi /etc/hosts.allow

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

#

# Allow Policy

#

ALL: 127. 192.168.20.200

sshd: 192.168.20. EXCEPT 192.168.20.50

 

(Local : Allow) 192.168.20.200(linux200 --> linux200)

# ssh 192.168.20.200

# exit

 

(Remote: Deny ) 192.168.20.50(KaliLinux --> linux200)

# ssh 192.168.20.200

ssh_exchange_identification: Connection closed by remote host

 

(Remote: Allow) 192.168.20.100(firewall --> linux200)

# ssh 192.168.20.200

# exit

 

 

 

# vi /etc/hosts.allow

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

#

# Allow Policy

#

ALL: 127. 192.168.20.200

sshd: 192.168.20. EXCEPT 192.168.20.50

vsftpd: 192.168.20. EXCEPT 192.168.20.50

 

(Local : Allow) 192.168.20.200(linux200 --> linux200)

# ftp 192.168.20.200

ftp> quit

 

(Remote: Deny ) 192.168.20.50(KaliLinux --> linux200)

# ftp 192.168.20.200

421 Service not available.

ftp> quit

 

(Remote: Allow) 192.168.20.100(firewall --> linux200)

# ftp 192.168.20.200

ftp> quit

 

# vi /etc/hosts.allow

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

#

# Allow Policy

#

ALL: 127. 192.168.20.200

sshd: 192.168.20. EXCEPT 192.168.20.50

vsftpd: 192.168.20. EXCEPT 192.168.20.50

telnetd: 192.168.20.50

 

(Local : Allow) 192.168.20.200(linux200 --> linux200)

# telnet 192.168.20.200

# exit

 

(Remote: Allow) 192.168.20.50(KaliLinux --> linux200)

# telnet 192.168.20.200

# exit

 

(Remote: Deny ) 192.168.20.100(firewall --> linux200)

# telnet 192.168.20.200

Connection closed by foreign host.

 

 

 

 

(192.168.20.200) linux200

 

(첫번째 테스트)

# vi /etc/hosts.allow

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

#

# Allow Policy

#

ALL: 127. 192.168.20.200

#sshd: 192.168.20. EXCEPT 192.168.20.50

sshd: 192.168.20. : spawn /bin/echo `/bin/date` from %h >> /var/log/sshd.log

vsftpd: 192.168.20. EXCEPT 192.168.20.50

telnetd: 192.168.20.50

 

(Local) 192.168.20.200(linux200)

[TERM1] # touch /var/log/sshd.log

# tail -f /var/log/sshd.log

Tue Jan 20 12:44:14 KST 2015 from 192.168.20.50

Tue Jan 20 12:44:44 KST 2015 from 192.168.20.100

 

(Remote: Allow) 192.168.20.50(KaliLinux --> linux200)

# ssh 192.168.20.200

# exit

 

(Remote: Allow) 192.168.20.100(firewall --> linux200)

# ssh 192.168.20.200

# exit

 

 


(두번째 테스트)

# mkdir /etc/deny-banner

# vi /etc/deny-banner/telnetd

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

Attention, this is a private host!

To gain access email: root@example.com

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

 

# cat /etc/hosts.allow | grep telnetd

telnetd: 192.168.20.50

 

# vi /etc/hosts.deny

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

#

# All Service Denied

#

ALL: ALL: banners /etc/deny-banner

 

 

 

(firewall) 192.168.20.100

 

# telnet 192.168.20.200

Trying 192.168.20.200...

Connected to linux200 (192.168.20.200).

Escape character is '^]'.

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

Attention, this is a private host!

To gain access email: root@example.com

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

Connection closed by foreign host.

-> 클라이언트 쪽에서 테스트 해 본다.

 

 

 

 

 


Linux(KaliLinux)

192.168.10.50

A

|

|

V

(eth0:1)192.168.10.200

Linux(firewall) <----------> Linux(linux200) <----------> Linux(KaliLinux)

192.168.20.100 (eth0)192.168.20.200 192.168.20.50

 

[그림] 실습 환경

 

 

 

(linux200) 192.168.20.200

eth0:1 (가상 인터페이스) 생성

KaliLinux 통신이 되는지 확인

 

() 가상인터페이스(eth0:1) 생성

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:D1:F3:EE

inet addr:192.168.20.200 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fed1:f3ee/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:403 errors:0 dropped:0 overruns:0 frame:0

TX packets:67 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:43044 (42.0 KiB) TX bytes:8140 (7.9 KiB)

Interrupt:67 Base address:0x2024

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:7192 errors:0 dropped:0 overruns:0 frame:0

TX packets:7192 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:7979763 (7.6 MiB) TX bytes:7979763 (7.6 MiB)

 

# cd /etc/sysconfig/network-scripts

# ls

ifcfg-eth0 ifdown-isdn@ ifup-aliases* ifup-plip* ifup-wireless*

ifcfg-lo ifdown-post* ifup-bnep* ifup-plusb* init.ipv6-global*

ifdown@ ifdown-ppp* ifup-eth* ifup-post* net.hotplug*

ifdown-bnep* ifdown-routes* ifup-ippp* ifup-ppp* network-functions

ifdown-eth* ifdown-sit* ifup-ipsec* ifup-routes* network-functions-ipv6

ifdown-ippp* ifdown-sl* ifup-ipv6* ifup-sit*

ifdown-ipsec* ifdown-tunnel* ifup-ipx* ifup-sl*

ifdown-ipv6* ifup@ ifup-isdn@ ifup-tunnel*

 

# cp ifcfg-eth0 ifcfg-eth0:1

# vi ifcfg-eth0:1

# Advanced Micro Devices [AMD] 79c970 [PCnet32 LANCE]

[수정전]

DEVICE=eth0

BOOTPROTO=none

BROADCAST=192.168.20.255

IPADDR=192.168.20.200

IPV6INIT=yes

IPV6_AUTOCONF=yes

NETMASK=255.255.255.0

NETWORK=192.168.20.0

ONBOOT=yes

GATEWAY=192.168.20.100

TYPE=Ethernet

HWADDR=00:0c:29:d1:f3:ee

[수정후]

DEVICE=eth0:1

BOOTPROTO=none

BROADCAST=192.168.10.255

IPADDR=192.168.10.200

NETMASK=255.255.255.0

NETWORK=192.168.10.0

ONBOOT=yes

TYPE=Ethernet

# service network restart

# ifconfig

eth0 Link encap:Ethernet HWaddr 00:0C:29:D1:F3:EE

inet addr:192.168.20.200 Bcast:192.168.20.255 Mask:255.255.255.0

inet6 addr: fe80::20c:29ff:fed1:f3ee/64 Scope:Link

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

RX packets:428 errors:0 dropped:0 overruns:0 frame:0

TX packets:100 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:45978 (44.9 KiB) TX bytes:13947 (13.6 KiB)

Interrupt:67 Base address:0x2024

 

eth0:1 Link encap:Ethernet HWaddr 00:0C:29:D1:F3:EE

inet addr:192.168.10.200 Bcast:192.168.10.255 Mask:255.255.255.0

UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1

Interrupt:67 Base address:0x2024

 

lo Link encap:Local Loopback

inet addr:127.0.0.1 Mask:255.0.0.0

inet6 addr: ::1/128 Scope:Host

UP LOOPBACK RUNNING MTU:16436 Metric:1

RX packets:7192 errors:0 dropped:0 overruns:0 frame:0

TX packets:7192 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:0

RX bytes:7979763 (7.6 MiB) TX bytes:7979763 (7.6 MiB)

 

() KaliLinux와 통신이 되지는 확인

# ping -c 1 192.168.10.50

PING 192.168.10.50 (192.168.10.50) 56(84) bytes of data.

64 bytes from 192.168.10.50: icmp_seq=1 ttl=64 time=3.31 ms

 

--- 192.168.10.50 ping statistics ---

1 packets transmitted, 1 received, 0% packet loss, time 0ms

rtt min/avg/max/mdev = 3.312/3.312/3.312/0.000 ms

 

[EX1] FTP(vsftpd) 서비스 제어

 

(설정파일 백업)

# mv /etc/hosts.allow /etc/hosts.allow.old

# mv /etc/hosts.deny /etc/hosts.deny.old

 

(1) 정책 설정(FTP(vsftpd) 서비스 제어)

KaliLinux(192.168.20.50)allow, 나머지 deny

 

(2) 설정 확인

[ 0 ] : [KaliLinux(192.168.20.50 -> 192.168.20.200)] # ftp 192.168.20.200

[ X ] : [KaliLinux(192.168.10.50 -> 192.168.10.200) # ftp 192.168.10.200

[ X ] : [firewall(192.168.20.100 -> 192.168.20.200) # ftp 192.168.20.200

[EX2] telnet(telnetd) 서비스 제어

 

(1) 정책 설정(telnet(telnetd))

192.168.20.0/24 대역만 allow, 나머지 deny

 

(2) 설정 확인

[ 0 ] : [KaliLinux(192.168.20.50 -> 192.168.20.200)] # telnet 192.168.20.200

[ X ] : [KaliLinux(192.168.10.50 -> 192.168.10.200) - # telnet 192.168.10.200

[ 0 ] : [firewall(192.168.20.100 -> 192.168.20.200) - # telnet 192.168.20.200

 

[EX3] ssh(sshd) 서비스 제어

 

(1) 정책 설정

192.168.10.50 allow, 나머지 deny

 

(2) 설정 확인

[ X ] : [KaliLinux(192.168.20.50 -> 192.168.20.200)] # ssh 192.168.20.200

[ 0 ] : [KaliLinux(192.168.10.50 -> 192.168.10.200) - # ssh 192.168.10.200

[ X ] : [firewall(192.168.20.100 -> 192.168.20.200) - # ssh 192.168.20.200

 

 

 

 

 

 

[참고] 실무 예

 

telnet 서비스가 반드시 필요하다(고객의 요청)

-> 호스트/네트워크 접근 제어 + 사용자 접근 제어

-> 호스트/네트워크 접근 제어 (--> tcp_wrappers)

-> 사용자 접근 제어 (--> /etc/securetty)

 

- vsftpd(21)

- sshd(22)

- telnetd(23)

 

# vi /etc/hosts.allow

---------------------------------

vsftpd: 192.168.20.50

sshd: 192.168.20.

telnetd: 192.168.10.50

---------------------------------

# vi /etc/hosts.deny

---------------------------------

vsftpd: ALL

sshd: ALL

telnetd: ALL

---------------------------------

 

(주의) tcp_wrapper 사용시 주의 사항

* /etc/hosts.allow, /etc/hosts.deny 파일에 설정되고 저장되면 적용된다.

 

 

 

 

 

 

[EX4] portmap(NFS) 제어

 

IT 용어 설명

- www.ktword.co.kr

- www.terms.co.kr

- dic.naver.com

-----------------------------------------------

스토리지(Storage)

- DAS(Direct Attached Storage)

- internal

- external

- NAS(Network Attached Storage)

- SAN(Storage Area Network)

 

자원(Resource)

- NFS(Network File System)

NFSv1/v2/v3/v4

- CIFS/SMB(Common Internet File System)

-----------------------------------------------

 

 

---- NFS Server ----- ----- NFS Client -----

share mount

# vi /etc/exports

/share client(rw)

# exportfs -ar

# mount server:/share /mnt/linuxXXX

 

--------------------- ----------------------

 

# vi /etc/hosts.allow

portmap: <NFS Client's IP>

mountd: <NFS Client's IP>

# vi /etc/hosts.deny

portmap: ALL

mountd: ALL

 

or

 

# vi /etc/hosts.allow

portmap: <NFS Client's IP>

# vi /etc/hosts.deny

portmap: ALL

 

 

 

(1) 정책 설정

192.168.20.100 allow, 나머지 deny

 

(2) 설정 확인

[ 0 ] : [firewall(192.168.20.100 -> 192.168.20.200) # showmount -e 192.168.20.200 # mkdir -p /mnt/linux200 # mount 192.168.20.200:/share /mnt/linux200 # df -h # cd ; umount /mnt/linux200

[ X ] : [firewall(192.168.10.100 -> 192.168.20.200) # showmount -e 192.168.10.200 # mkdir -p /mnt/linux200 # mount 192.168.10.200:/share /mnt/linux200 # df -h # cd ; umount /mnt/linux200

 

(주의) 테스트가 끝나면 반드시 umount 한다.

# cd ; umount /mnt/linux200

 

 

[EX5] MAIL(sendmail) 제어

 

(1) 정책 설정

모든 지역에 서비스가 allow 되도록 설정

 

(2) 설정 확인

[ 0 ] : firewall(192.168.20.100) # telnet 192.168.20.200 25 # telnet 192.168.20.200 110

[ 0 ] : KaliLinux(192.168.10.50) # telnet 192.168.10.200 25 # telnet 192.168.10.200 110

 

 

 


[EX6] SAMBA 서비스 제어

 

SAMBA 서비스는 tcp wrapper 의해서 제어 되지 않는다.

따라서 Firewall(iptables)을 통해 제어해야 한다.

 

 

 

[EX7] DNS 서비스 제어

DNS 서비스는 tcp_wrapper 의해서 제어 되지 않는다.

따라서 Firewall(iptables)을 통해 제어해야 한다.

 

 

 

[EX8] WEB 서비스 제어

WEB(httpd) 서비스는 tcp_wrapper 의해서 제어 되지 않는다.

따라서 Firewall(iptables)을 통해 제어해야 한다.

 

 

 

[EX9] POP3/IMAP 서비스 제어

POP3/IMAP(dovecot) 서비스는 tcp_wrapper 의해서 제어 되지 않는다.

따라서 Firewall(iptables)을 통해 제어해야 한다.

 

 

 

[EX10] 기타 서비스 제어

syslogd(포트 514), yum(포트 20,21,80,53), dhcpd(포트 67,68), ntpd(123)

위의 서비스 모두 tcp_wrapper 의해서 제어 되지 않는다.





[EX11] /etc/hosts.allow, /etc/hosts.deny 파일 예제

 

# vi /etc/hosts.allow

#

# hosts.allow This file describes the names of the hosts which are

# allowed to use the local INET services, as decided

# by the '/usr/sbin/tcpd' server.

#

#

# (1) LOCAL(127.0.0.1) Allow Policy

#

ALL: 127. 172.16.9.2XX

#

# (2) FTP(vsftpd) Policy

#

vsftpd: 172.16.9.X

#

# (3) telnet(krb5-telnet) Policy

#

telnetd: 172.16. : spawn /bin/echo `/bin/date` from %h >> /var/log/telnet.log

#

# (4) sshd Policy

#

sshd: 192.168.10.1XX : spawn /bin/echo `/bin/date` from %h >> /var/log/ssh.log

#

# (5) NFS(mountd,portmap) policy

#

portmap: 192.168.10.1XX /* portmap 만 정의해도 된다. */

mountd: 192.168.10.1XX /* /etc/hosts.deny 파일에 ALL: ALL 정의한 경우 사용한다. */

#

# (6) MAIL(sendmail) policy

#

sendmail: ALL /* dovecot 서비스는 tcp_wrapper 의해서 제어 되지 않는다. */

 

# vi /etc/hosts.deny

#

# hosts.deny This file describes the names of the hosts which are

# *not* allowed to use the local INET services, as decided

# by the '/usr/sbin/tcpd' server.

#

# The portmap line is redundant, but it is left to remind you that

# the new secure portmap uses hosts.deny and hosts.allow. In particular

# you should know that NFS uses portmap!

#

# All Service Denied

#

vsftpd: ALL

telnetd: ALL

sshd: ALL

portmap: ALL

mountd: ALL

sendmail: ALL

 

 

 

 

 

 



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160802 Snort  (0) 2016.08.02
20160801 IDS  (0) 2016.08.01
20160801 NTP  (0) 2016.08.01
20160729 방화벽  (0) 2016.07.29
20160728 방화벽  (0) 2016.07.28
Posted by 22Hz
, |

NTP(Network Time Protocol)

 

 

 

 

 

 

 

윈도우(Windows XP) 시간 동기화

 

1

NTP 서버 필요성

 

많은 네트워크 프로그램들은 시간 동기화가 필요하게 된다. 네트워크 상에서 서로 연동하는 시스템들 간에 시간이 일치 하지 않게 된다면 다수의 시스템 장애처리, 성능카운트, 분석, 로깅등 수많은 문제점을 갖게된다.

자원 공유 서버(NFS Server)

데이터베이스 서버(DB Server)

로그 서버(Logging Server)

NMS 프로그램(Network Management Solution)

암호화(Encyption)

기타

===== WebServerA ===== ===== NFS Server ====

Date: 12:00 12:10

/p/file1(12:10) /source/file1(12:10)

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

A

===== WebServerB ===== |

Date: 12:40 +---- file1 생성

/p/file1(12:10)

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

[그림] 서버간의 시간 동기화 이유

 

 

[참고] 실무에서 많이 사용하고 있는 방법 예

실무에서는 rdate 명령어나 ntpdate 명령어를 통해 서버간의 시간을 동기화하는 방법이 많이 사용되고 있다.

 

실무에서 서버의 시간을 동기화 하기 위해서 가장 많이 사용하는 방법

rdate 명령어 사용하는 방법 -> crontab

ntpdate 명령어 사용하는 방법 -> crontab

 

# cat /etc/resolv.conf

nameserver 168.126.63.1

 

# rdate -s time.bora.net (# rdate -s 172.16.9.252)

Thu Apr 30 12:01:49 2009

[참고] rdate 서버: time-dgram, time-stream

or

# ntpdate -b time.bora.net (# ntpdate -b 172.16.9.252)

28 Oct 18:08:50 ntpdate[5833]: step time server 203.248.240.140 offset 2.706436 sec

[참고] NTP 서버 구축

 

위와 같이 rdate/ntpdate 명령어를 사용하는 방법을 실무에서는 가장 많이 사용하고 있으면, 명령어들 수행이 잘 된다면, crontab 파일에 등록하여 정기적으로 서버의 시간을 동기화 할 수 있도록 설정한다. crontab 파일에 등록할 때는 시간을 동기화 해야 하는 시간이 중요하며, 동기화 시점은 그날의 시작하는 시간으로 설정하는 것을 권장한다.

# crontab -e

1 0 * * * rdate -s time.bora.net (time.bora.net: 210.120.246.46)

or

1 0 * * * ntpdate -b time.kriss.re.kr

 

(결론)

rdate 명령어 보다는 ntpdate 명령어를 사용하는 것을 권장한다.

crontab 파일에 등록할 때 그날의 01분에 수행하도록 하는 것을 권장한다.

 

 

# vi /root/bin/date.sh

#!/bin/bash

 

echo "=== Remote Time ==="

rdate -p 172.16.9.252

echo "=== Local Time ==="

date

echo

 

# /root/bin/date.sh

-> 시간 정보 확인

 

 

 

 

 

2

NTP 서버 개요

 

NTP (network time protocol, 네트웍 시간 프로토콜)

NTP는 네트웍으로 연결되어 있는 컴퓨터들끼리 클록 시각을 동기화시키는데 사용되는 프로토콜이다. NTP는 미국 델라웨어 대학의 데이빗 밀스에 의해 처음 개발되었으나, 이제는 인터넷 표준이 되었다. NTP는 컴퓨터 클록 시간을 1/1000 초 이하까지 동기화시키기 위해 협정 세계시각(UTC)을 사용한다.

컴퓨터 네트웍 전반에 걸쳐 정확한 시각을 유지하는 것은 여러 가지 이유로 중요한데, 그 이유는 심지어 수십 분의 1초 정도의 차이만으로도 큰 문제가 발생될 수 있기 때문이다. 예를 들어 협정 세계시에 기반을 두면, 지역적으로 분산된 업무처리 환경에서도 작업 순서가 정확히 유지될 수 있다. 보안 메커니즘 역시 네트웍 전체에 걸쳐 협정 세계시에 기반을 두고 있다. 여러 대의 컴퓨터가 하나의 파일 시스템을 수정하는 것 역시 정확히 동기화된 클록 시각에 의존해야 한다. 항공기의 운항 궤적을 그림으로 표시해 주는 항공관제 시스템에도 매우 정확한 시간측정이 요구되는 것은 당연하다.

협정세계 시각은 무선이나 위성 시스템 등, 여러 가지 방법으로 얻어진다. GPS나 정부기관 등과 같은 특수한 수신자들은 보다 높은 수준의 서비스를 이용하는 것이 가능하지만,모든 컴퓨터에 수신기를 장착하는 것은 비경제적이며, 현실성이 없다. 그 대신에, 시각 서버로 지정된 컴퓨터들에만 수신기를 장착하고, 이 서버들과 네트웍으로 연결되어 있는 컴퓨터들의 클록 시각은 NTP와 같은 프로토콜을 사용하여 동기화하는 것이다.

협정세계시로부터 떨어져 있는 수준을 표시하기 위해 흔히 계층번호를 쓰는데, 0번 계층은 전용 송신기 또는 위성 위치추적 시스템으로부터 수신된 실제 시각인 무선 클록을, 1번 계층은 이 무선 클록과 직접 연결되어 있는 컴퓨터의 클록을, 2번 계층은 1번 계층으로부터 시각을 받은 컴퓨터 등으로 원천 협정 세계시로부터 멀수록 계층 번호가 커져 간다.

NTP라는 용어는, 프로토콜과 컴퓨터상에서 실행되는 클라이언트/서버 프로그램, 둘 모두에 대해 사용된다. 프로그램은 사용자에 의해 NTP 클라이언트, NTP 서버, 또는 둘 모두로 해석될 수 있다. NTP 클라이언트는 시각 서버에 정확한 현재 시각을 교환할 것을 요구한다. 이 교환의 결과를 통해, 클라이언트는 서버의 시각과의 차이를 이용하여 링크 지연시간을 계산할 수 있으며, 자신의 클록을 서버에 있는 클록과 일치하도록 조정할 수 있다. 하나의 규칙으로서, 처음 클록을 맞추기 위해서는 5~10분 동안 모두 6번의 시각 교환이 요구된다. 일단 시각 동기화가 끝나면, 클라이언트는 매 10분마다 메시지 교환을 통해 클록을 수정한다. 클록 동기화의 신뢰도 및 정확도를 높이기 위해, 여러 대의 서로 다른 서버와 다양한 네트웍 경로가 사용된다. 클라이언트/서버 동기화에 아울러, NTP는 브로드캐스트를 통한 컴퓨터 클록 동기화도 지원한다. NTP는 매우 높은 수준의 내고장성과 확장 가능성을 염두에 두고 설계되었다.

NTP 서버에서 사용되는 용어에 대해 알아보자.

(1). 기본적인 용어

Reference Clock - GMT, UTC과 같이 표준시간(기준시간) 또는 참고 시간

(: 한국 : GMT/UTC + 9 시간)

Strata - NTP 서버의 계층적 구조

Stratum-1 Server - NTP 1계층 서버

Stratum-2 Server - NTP 2계층 서버

... -15 .... - NTP 15계층 서버(15까지 존재)

Drift File - PPM(Parts-Per-Million)단위로 오프셋에 일치하는 단일 부동 소수

점이 들어가 있다. (: /var/ntp/ntp.drift)

xntpd - NTP 서버/클라이언트 데몬

ntp.conf - NTP 서버/클라이언트 주 설정 파일

(2). 추가적인 용어

Resolution - 시간 제공 장치에서 사용하는 시간의 최소 단위.

() 손목시계의 Resolution : 1

Precision - 컴퓨터 프로그램에서 사용하는 시간의 최소 단위.

Accuracy - 시간의 정확성. 기준시간(UTC)과 얼마나 근접한가를 나타냄.

Jitter - 시간을 측정했을 때 생기는 오차 중 작은 값.

Wander - 시간을 측정했을 때 생기는 오차 중 큰 값.

[참고] UTC & GMT

UTC(Universal Time Coordinate) 협정 세계시, 그리니치 표준시 대신 방송에 사용되는 표준시. 협정 세계시는 국제 사회가 사용하는 과학적 시간의 표준입니다. 197211일부터시행된협정세계시에서는67년국제도량형총회가정한세슘원자의 진동수에 의거한 초의 길이가 그 기준(원자초)으로 쓰인다. 그 때까지 시간의 기준으로는 지구의 자전에 의한 평균태양시와 지구의 공전에 의한 태양년에서 산출한 초의 길이가 쓰였다. 그리니치표준시(GMT)는 원래 평균태양시를 기준으로 한 것이었다. 따라서 원자시계를 표준으로 하면서부터 GMT라는 명칭이 실체(實體)를 바르게 나타내지 못하는 불합리한 점이 생겼다. 이러한 문제를 없애기 위해서 1978년 국제무선통신자문위원회(CCIS) 총회는 통신분야에서는 금후 그리니치평균시를 협정세계시(UTC)로 바꾸어 쓰자는 권고안을 채택하였다.

GMT(Greenwich Mean Time) 그리니치 표준시. 그리니치천문대를 지나는 본초자오선(그리니치자오선)을 기준으로 하는 시. 약호 GMT. 약칭하여 그리니치시라고도 한다. 1925년 이전의 그리니치시는 정오(正午)0시로하여 시간을 재기 시작하는 방식의 천문학용 평균태양시의 명칭이었다. 이에 반해 일상생활에서는 자정을0시로하여시간을재는방식이사용되었으며,이것을그리니치상용시(GCT)라고 하였다. 192511일국제천문연합에서는그리니치시를12시간앞당겨그리니치 상용시와 일치시켰으며, 이를 세계시(世界時)라고 하여 전세계 공통의 표준시로 사용하였다. 그러나 지구의 자전을 근거로 한 이 세계시는 수정시계나 원자시계와 비교한 결과 지구 자전의 불규칙성에 의한 오차가 있으므로 1972년 이후에는 새로이 협정세계시가 세계표준시로 사용되었다. 협정세계시란 세계시와는 달리 원자 방사(放射)의 진동수를 기준으로 하고, 원자시의 초()를 세분하여 세계시와의 차이가 0.9초 이내가 되도록 만든 것이다.

 

[참고] 참고 URL(, 시간의 인식, 시의 척도, 시법, 하루의 시작, 보시등)

http://kr.dic.yahoo.com/search/enc/result.html?p=UTC&pk=15348300&subtype=&type=enc&field=id

[참고] Stratum 1 / Stratum 2

http://www.ntp.org

Stratum 1 Server : http://support.ntp.org/bin/view/Servers/StratumOneTimeServers

Stratum 2 Server : http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers

3

NTP 서버 동작 원리(NTP Server Concept)

 

(1). 서비스 관리

(현재) # service ntpd restart

(부팅) # chkconfig ntpd on

(2). NTP Network Transfer Time Check

NTP Client NTP Server

| |

T1 | ------------------> | T2

| |

| |

T4 | <------------------ | T3

| |

| |

네트워크에서 보낸시간 = [(T2-T1)+(T4-T3)] / 2

(a). NTP ClientNTP 서버에 현재 시간을 요구하는 요청을 보낼 때, 패킷에 클

라이언트의 현재 시간(T1)을 포함하여 보낸다.

(b). 클라이언트의 요청을 받은 NTP 서버는 요청을 받았을 때의 서버 시간(T2)

패킷에 포함한다.

(c). NTP 서버는 현재 UTC 시간을 패킷에 포함하고, 클라리언트로 보내는 순가의

서버 시간(T3)도 패킷에 포함하여 클라이언트의 요청에 응답한다.

(d). 클라이언트는 서버의 응답을 받는 순간의 시간(T4)과 나머지 시간들을 이용

하여 네트워크에서 얼만큼의 시간을 보냈는지 판단하여 UTC 시간에 더한 후

시스템의 시간으로 설정한다.

4

NTP 서버/클라이언트 실습

 

 

NTP 서버/클라이언트 실습(CentOS 5.X on VMWare)

 

(실습 환경)

NTP Main Server : (Bridge, eth0) 172.16.9.252

 

NTP Client : (Bridge, eth0) 172.16.9.2XX

 

NTP Client : (Bridge, eth0) 172.16.9.1XX

 

 

(NTP Main Server) 172.16.9.252

 

[참고] NTP 프로그램 설치

# rpm -qa | grep ntp

# yum -y install ntp

 

NTP 주 설정 파일 설정

# vi /etc/ntp.conf

# Permit time synchronization with our time source, but do not

# permit the source to query or modify the service on this system.

restrict default kod nomodify notrap nopeer noquery

restrict -6 default kod nomodify notrap nopeer noquery

 

# Permit all access over the loopback interface. This could

# be tightened as well, but to do so would effect some of

# the administrative functions.

restrict 127.0.0.1

restrict -6 ::1

 

# Hosts on local network are less restricted.

#---> #restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

restrict 172.16.0.0 mask 255.255.0.0 nomodify notrap

 

# Use public servers from the pool.ntp.org project.

# Please consider joining the pool (http://www.pool.ntp.org/join.html).

#---> server 0.centos.pool.ntp.org

#---> server 1.centos.pool.ntp.org

#---> server 2.centos.pool.ntp.org

 

#broadcast 192.168.1.255 key 42 # broadcast server

#broadcastclient # broadcast client

#broadcast 224.0.1.1 key 42 # multicast server

#multicastclient 224.0.1.1 # multicast client

#manycastserver 239.255.254.254 # manycast server

#manycastclient 239.255.254.254 key 42 # manycast client

 

# Undisciplined Local Clock. This is a fake driver intended for backup

# and when no outside source of synchronized time is available.

server 127.127.1.0 # local clock

#---> fudge 127.127.1.0 stratum 10

 

# Drift file. Put this in a directory which the daemon can write to.

# No symbolic links allowed, either, since the daemon updates the file

# by creating a temporary in the same directory and then rename()'ing

# it to the file.

driftfile /var/lib/ntp/drift

 

# Key file containing the keys and key identifiers used when operating

# with symmetric key cryptography.

keys /etc/ntp/keys

 

# Specify the key identifiers which are trusted.

#trustedkey 4 8 42

 

# Specify the key identifier to use with the ntpdc utility.

#requestkey 8

 

# Specify the key identifier to use with the ntpq utility.

#controlkey 8

 

서비스 데몬 start 및 확인

# service ntpd restart (# chkconfig ntpd on)

Shutting down ntpd: [FAILED]

Starting ntpd: [ OK ]

 

# pgrep -lf ntpd

5208 ntpd -u ntp:ntp -p /var/run/ntpd.pid -g

 

설정 확인

# ntpq -p (# ntp -pn)

remote refid st t when poll reach delay offset jitter

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

LOCAL(0) .LOCL. 5 l 6 64 1 0.000 0.000 0.001

 

 

 

(NTP Client) 172.16.9.2XX

 

NTP 메인 서버에 시간을 동기화 시킨다.

 

# vi /root/bin/date.sh

-------------------------------------------

#!/bin/bash

echo "=== Remote Time ==="

rdate -p 172.16.9.252

echo "=== Local Time ==="

date

-------------------------------------------

# chmod 755 /root/bin/date.sh

 

# rdate -s 172.16.9.252

# /root/bin/date.sh

-> 출력 내용 생략

 

NTP 프로그램 설치 확인

# rpm -qa | grep ntp (# vi /etc/resolv.conf ; yum -y install ntp)

ntp-4.2.2p1-15.el5.centos

 

# rpm -ql ntp (# rpm -qi ntp)

/etc/ntp

/etc/ntp.conf

/etc/ntp/keys

/etc/ntp/step-tickers

/etc/rc.d/init.d/ntpd

/etc/sysconfig/ntpd

/sbin/ntpd

/sbin/ntpdate

/usr/bin/ntpstat

/usr/sbin/ntp-keygen

/usr/sbin/ntp-wait

/usr/sbin/ntpd

/usr/sbin/ntpdate

/usr/sbin/ntpdc

/usr/sbin/ntpq

/usr/sbin/ntptime

/usr/sbin/ntptrace

/usr/sbin/sntp

/usr/sbin/tickadj

/usr/share/doc/ntp-4.2.2p1

/usr/share/doc/ntp-4.2.2p1/NEWS

/usr/share/doc/ntp-4.2.2p1/TODO

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

/usr/share/man/man5/ntp.conf.5.gz

/usr/share/man/man5/ntp_acc.5.gz

/usr/share/man/man5/ntp_auth.5.gz

/usr/share/man/man5/ntp_clock.5.gz

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

/var/lib/ntp

/var/lib/ntp/drift

 

/etc/ntp.conf 파일 설정 및 변경 사항 적용

# vi /etc/ntp.conf

# Permit time synchronization with our time source, but do not

# permit the source to query or modify the service on this system.

restrict default kod nomodify notrap nopeer noquery

restrict -6 default kod nomodify notrap nopeer noquery

 

# Permit all access over the loopback interface. This could

# be tightened as well, but to do so would effect some of

# the administrative functions.

restrict 127.0.0.1

restrict -6 ::1

 

# Hosts on local network are less restricted.

#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

 

# Use public servers from the pool.ntp.org project.

# Please consider joining the pool (http://www.pool.ntp.org/join.html).

#---> server 0.centos.pool.ntp.org

#---> server 1.centos.pool.ntp.org

#---> server 2.centos.pool.ntp.org

 

#broadcast 192.168.1.255 key 42 # broadcast server

#broadcastclient # broadcast client

#broadcast 224.0.1.1 key 42 # multicast server

#multicastclient 224.0.1.1 # multicast client

#manycastserver 239.255.254.254 # manycast server

#manycastclient 239.255.254.254 key 42 # manycast client

 

# Undisciplined Local Clock. This is a fake driver intended for backup

# and when no outside source of synchronized time is available.

#---> server 127.127.1.0 # local clock

#---> fudge 127.127.1.0 stratum 10

server 172.16.9.252 prefer

 

# Drift file. Put this in a directory which the daemon can write to.

# No symbolic links allowed, either, since the daemon updates the file

# by creating a temporary in the same directory and then rename()'ing

# it to the file.

driftfile /var/lib/ntp/drift

 

# Key file containing the keys and key identifiers used when operating

# with symmetric key cryptography.

keys /etc/ntp/keys

 

# Specify the key identifiers which are trusted.

#trustedkey 4 8 42

 

# Specify the key identifier to use with the ntpdc utility.

#requestkey 8

 

# Specify the key identifier to use with the ntpq utility.

#controlkey 8

 

서비스 데몬 start 및 확인

# service ntpd restart (# chkconfig ntpd on)

Shutting down ntpd: [FAILED]

Starting ntpd: [ OK ]

 

# pgrep -lf ntpd

5208 ntpd -u ntp:ntp -p /var/run/ntpd.pid -g

 

[참고] ntpd 데몬에 대해서

# man ntpd

-u user[:group]

Specify a user, and optionally a group, to switch to. This

option is only available if the OS supports to run the

server without full root privileges. Currently, this option

is supported under NetBSD (configure with --enable-

clockctl) and Linux (configure with enable-linuxcaps).

 

-p pidfile

Specify the name and path of the file used to record the

ntpd process ID. This is the same operation as the pidfile

pidfile configuration command.

 

-g Normally, ntpd exits with a message to the system log if

the offset exceeds the panic threshold, which is 1000 s by

default. This option allows the time to be set to any value

without restriction; however, this can happen only once. If

the threshold is exceeded after that, ntpd will exit with a

message to the system log. This option can be used with the

-q and -x options. See the tinker command for other

options.

 

NTP Peer 서버 설정 확인

# ntpq -p

remote refid st t when poll reach delay offset jitter

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

172.16.9.252 LOCAL(0) 6 u 14 64 1 2.450 0.964 0.001

 

[참고] ntpq 명령어

# man ntpq

-n Output all host addresses in dotted-quad numeric format

rather than converting to the canonical host names.

 

-p Print a list of the peers known to the server as well as a

summary of their state. This is equivalent to the peers

interactive command.

 

시간 동기화 실습

# date

Fri Oct 28 18:13:06 KST 2011

 

# date 10281813

Fri Oct 28 18:13:00 KST 2011

-> 서버와 약간 시간을 틀리게 설정합니다.

-> , 1분 이내의 시간으로 설정하셔야 빠르게 테스트가 가능합니다.

 

(필요하면 명령어 수행)

# cd ~/.ssh

# ls

# ssh-keygen

<ENTER>

<ENTER>

<ENTER>

# scp id_ras.pub 172.16.9.252:/root/.ssh/authorized_keys

# ssh 172.16.9.252 date

-> 암호를 물어 보지 않는다.

 

# ssh 172.16.9.252 date

root@172.16.9.252's password: (암호입력)

 

Fri Oct 28 18:15:28 KST 2011

 

# date

Fri Oct 28 18:14:56 KST 2011

 

# ntpq -pn

remote refid st t when poll reach delay offset jitter

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

*172.16.9.252 LOCAL(0) 6 u 18 64 77 0.264 0.008 15055.0

 

출력 결과 해석시

* 현재 NTP 서버와 동기화 중

+ NTP 서버와 통신은 가능하지만 현재 동기화는 하고 있지 않음

- NTP 서버와 통신은 가능하지만 동기화 목록에서 제외된 경우

blank or INIT NTP 서버와 통신이 불가능

 

reach = reachability reach 값은 타임서버에 완전히 접속하기 위한 8진수로 377이어야 합니다.

delay = delay delay 값은 양의 수여야 하며 가능한 작은 값이어야 합니다.

 

..... (10분 정도 후에(보통은 2 ~ 3분정도)) ......

 

(필요하면 명령어 수행)

# while true

> do

> echo "------------`date`--------------“

> ntpq p

> sleep 2

> done

 

# ntpq pn

remote refid st t when poll reach delay offset jitter

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

172.16.9.252 LOCAL(0) 6 u 11 64 377 0.412 -0.002 25447.6

 

# ssh 172.16.9.252 date

root@172.16.9.252's password: (암호입력)

Fri Oct 28 18:22:51 KST 2011

 

# date

Fri Oct 28 18:22:52 KST 2011

 

 

 

(NTP Client) 172.16.9.1XX

 

-> 같은 방법으로 설정하면 된다.

 

[실무예1]

 

외국에서 서버가 들어온 경우(EX: 이스라엘) 서버를 Power ON 하고 부팅이 된 이후에 시간을 확인하면

-> 항상 1시간 정도 빠른 경우

-> 썸머타임 설정

-> 로케일 설정(1시간 정도 차이가 나는 나라 UTC+8 or UTC+10)

 

 

 

[실무예2]

 

윈도우 서버가 TIME 서버(NTP 서버)인 경우 리눅스 서버가 시간 동기화를 하는 경우

-> rdate 명령어가 윈도우에는 없다. 리눅스 서버에서 NTP Client 설정을 통해 동기화 한다.

-> ntp.conf 통해서 윈도우서버 지정

 

 

 

[실무예3]

 

많은 서버를 통해 단일 서비스를 제공하는 서버의 경우에 시간 동기화는?

-> 많은 서버들은 외부와 통신이 되지 않는다.

-> ------ (공인IP) -- L4 -- (사설IP) ------ (사설IP) -- 많은서버

 

 

 

5

참고 사이트

 

 

참고 사이트 1(NTP 자료 사이트)

http://www.ntp.org

http://www.kipt.co.kr/index.php?doc=bbs/gnuboard.php&bo_table=pds&page=1&wr_id=24

http://kr.dic.yahoo.com/search/enc/result.html?p=UTC&pk=15348300&subtype=&type=enc&field=id

http://support.ntp.org/bin/view/Servers/StratumOneTimeServers

http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers

 

 

참고 사이트 2(NTP 설정시 참고 사이트)

http://hook.tistory.com/275

http://blog.naver.com/junix?Redirect=Log&logNo=80087384442

 

 

참고 사이트 3(NTP 서버 목록)

http://www.pool.ntp.org/zone/asia

server gps.bora.net

server ntp1.cs.pusan.ac.kr

server ntp.ewha.net

server ntp.bora.net

server time.bora.net

server time.nuri.net

server ntp1.gngidc.net

server ntp2.gngidc.net

server time.kriss.re.kr

 

 

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160801 IDS  (0) 2016.08.01
20160801 TCP Wrapper  (0) 2016.08.01
20160729 방화벽  (0) 2016.07.29
20160728 방화벽  (0) 2016.07.28
20160728 로그보안  (0) 2016.07.28
Posted by 22Hz
, |

4

iptables 간단한 실습

 

 

(기본적인 사용법)

# iptables -L /* -L : list */

# iptables -L -v

 

# iptables -F /* -F : Flush */

# iptables -F INPUT

 

# iptables -P INPUT DROP /* -P : Policy */

# iptables -P INPUT ACCEPT

 

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

 

# service iptables save

# service iptables start

# service iptables stop

# service iptables restart

# service iptables status

 

# chkconfig --list iptables

# chkconfig iptables on

 

파일 이름: /etc/sysconfig/iptables

 

 

[EX1] 기본적인 사용법

 

(전제 조건)

방화벽 서버에서는 다음과 같은 명령어가 수행되어 있는 것으로 가정한다.

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

nmap 설치가 되어 있어야 한다.

# nmap localhost (# vi /etc/resolv.conf ; yum -y install nmap)

# nmap -V

tcp_wrappers 기능은 사용하지 않는다.

# cat /etc/hosts.allow

# cat /etc/hosts.deny

 

현재 iptables 확인

# iptables -h

iptables v1.3.5

 

Usage: iptables -[AD] chain rule-specification [options]

iptables -[RI] chain rulenum rule-specification [options]

iptables -D chain rulenum [options]

iptables -[LFZ] [chain] [options]

iptables -[NX] chain

iptables -E old-chain-name new-chain-name

iptables -P chain target [options]

iptables -h (print this help information)

 

Commands:

Either long or short options are allowed.

--append -A chain Append to chain

--delete -D chain Delete matching rule from chain

--delete -D chain rulenum

Delete rule rulenum (1 = first) from chain

--insert -I chain [rulenum]

Insert in chain as rulenum (default 1=first)

--replace -R chain rulenum

Replace rule rulenum (1 = first) in chain

--list -L [chain] List the rules in a chain or all chains

--flush -F [chain] Delete all rules in chain or all chains

--zero -Z [chain] Zero counters in chain or all chains

--new -N chain Create a new user-defined chain

--delete-chain

-X [chain] Delete a user-defined chain

--policy -P chain target

Change policy on chain to target

--rename-chain

-E old-chain new-chain

Change chain name, (moving any references)

Options:

--proto -p [!] proto protocol: by number or name, eg. `tcp'

--source -s [!] address[/mask]

source specification

--destination -d [!] address[/mask]

destination specification

--in-interface -i [!] input name[+]

network interface name ([+] for wildcard)

--jump -j target

target for rule (may load target extension)

--goto -g chain

jump to chain with no return

--match -m match

extended match (may load extension)

--numeric -n numeric output of addresses and ports

--out-interface -o [!] output name[+]

network interface name ([+] for wildcard)

--table -t table table to manipulate (default: `filter')

--verbose -v verbose mode

--line-numbers print line numbers when listing

--exact -x expand numbers (display exact values)

[!] --fragment -f match second or further fragments only

--modprobe=<command> try to insert modules using this command

--set-counters PKTS BYTES set the counter during insert/append

[!] --version -V print package version.

 

# uname -a

Linux linux249.example.com 2.6.18-164.el5 #1 SMP Thu Sep 3 03:33:56 EDT 2009 i686 athlon i386 GNU/Linux

 

# iptables -V

iptables v1.3.5

 

# iptables -L (# iptables -L -t filter)

Chain INPUT (policy ACCEPT)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

INPUT 체인에 대한 기본 정책 설정

# iptables -P INPUT DROP

# iptables -L

Chain INPUT (policy DROP)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

INPUT 체인에 규칙(Rules) 추가

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

# iptables -L (# iptables -vL)

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT tcp -- anywhere anywhere tcp dpt:telnet

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

# service iptables status

Table: filter

Chain INPUT (policy DROP)

num target prot opt source destination

1 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:23

 

Chain FORWARD (policy ACCEPT)

num target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

num target prot opt source destination

/etc/sysconfig/iptable 파일에 저장

# ls -l /etc/sysconfig/iptables

ls: /etc/sysconfig/iptables: No such file or directory

 

# service iptables save

Saving firewall rules to /etc/sysconfig/iptables: [ OK ]

-> MEM 안에 들어 있는 iptables(firewall) 설정을 파일(/etc/sysconfig/iptables)에 저장한다.

 

# cat /etc/sysconfig/iptables

# Generated by iptables-save v1.3.5 on Tue Mar 30 02:44:34 2010

*filter

:INPUT DROP [2:470]

:FORWARD ACCEPT [0:0]

:OUTPUT ACCEPT [6522:278819]

-A INPUT -p tcp -m tcp --dport 23 -j ACCEPT

COMMIT

# Completed on Tue Mar 30 02:44:34 2010

-> 이 파일에 저장이 되면 부팅시에도 이 설정이 다시 올라온다.

-> 부팅시에

# chkconfig iptables on

# cat /etc/sysconfig/iptables

 

iptables Flush

# iptables -F (# iptables -F INPUT)

#

-> MEM 안의 Firwall 설정/(rules)flush 시킨다.

-> 파일(/etc/sysconfig/iptables)의 내용을 flush 시키는 것은 아니다.

 

# iptables -L

Chain INPUT (policy DROP)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

iptables 현재 start

# service iptables start

Flushing firewall rules: [ OK ]

Setting chains to policy ACCEPT: filter [ OK ]

Unloading iptables modules: [ OK ]

Applying iptables firewall rules: [ OK ]

Loading additional iptables modules: ip_conntrack_netbios_n[ OK ]

-> 서비스가 start 되면 설정 파일(/etc/sysconfig/iptables)을 다시 읽어 메모리상으로 로딩한다.

 

# iptables -L

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT tcp -- anywhere anywhere tcp dpt:telnet

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

 

 

iptables 서비스 현재 stop

# service iptables stop

Flushing firewall rules: [ OK ]

Setting chains to policy ACCEPT: filter [ OK ]

Unloading iptables modules: [ OK ]

-> /etc/sysconfig/iptables 파일이 삭제된것은 아니다.

-> 따라서 부팅이 되면 서비스가 다시 올라온다.

 

# iptables -L

Chain INPUT (policy ACCEPT)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

# cat /etc/sysconfig/iptables

# Generated by iptables-save v1.3.5 on Fri Aug 26 12:18:49 2011

*filter

:INPUT DROP [979:102009]

:FORWARD ACCEPT [0:0]

:OUTPUT ACCEPT [97:14696]

-A INPUT -p tcp -m tcp --dport 23 -j ACCEPT

COMMIT

# Completed on Fri Aug 26 12:18:49 2011

 

# chkconfig --list | grep iptables

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

 

# chkconfig iptables off

# chkconfig --list | grep iptables

iptables 0:off 1:off 2:off 3:off 4:off 5:off 6:off

-> 부팅시에 iptables OFF

 

# chkconfig iptables on

# chkconfig --list | grep iptables

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

 

방화벽 서비스 관리

(현재) # service iptables start/stop

(부팅) # chkconfig iptables on/off

 

작업하는 방법

(전제조건) /etc/sysconfig/iptables 파일이 존재하고 룰(rules)이 존재한다.

# iptables -A ......

# service iptables save

or

# vi /etc/sysconfig/iptables

# service iptables reload

 

 

 

 

 

5

iptables 방화벽 정책 실습

 

 

방화벽 정책을 세워보자.

 

/etc/sysconfig/iptables 파일을 사용하지 않고 따로 스크립트(EX: /root/bin/iptables.sh) 를 만들어서 사용하였다.

iptables 설정은 () 네트워크(네트워크 방화벽)쪽에서 설정할수 있거나 () 서버(서버 방화벽)에서 설정할 수 있거나 () 일반 PC(개인 방화벽)에서 설정할 수 있다.

이 문서에서는 서버 방화벽 형태의 룰(rules)에 대한 부분만을 다룬다.

 

 


 

[그림] 실습 구성도

 

 

서버 엔지니어가 관리하는 서버가 존재한다고 본다면, 그 서버는 여러가지 접근 제어 서비스(Access Control Service)를 받는 경우가 많다. 예를 들어 이런 서비스는 방화벽, IPS(침입차단시스템), IDS(침입탐지시스템), 스크리닝 라우터, 라우터의 ACL등이다. 하지만 이런 서비스는 외부에서 내부를 보호하기 위한 목적으로 주로 사용하고 있다. 내부에 있는 서버가 다른 내부의 서버에 대한 접근 제어에는 취약한 점이 많다. 이런경우 내부의 악의적인 사용자들에게 서버들이 노출되기 때문에 위험하다. 이런경우 서버 방화벽을 켜고 사용하게 되면 악의적인 내부 사용자들을 쉽게 방어할 수 있게 된 다. 특정한 서버와만 통신할수 있도록 설정하는것이다.

 

 

 

 

 

 

 

 

서버 방화벽 구성(Server Firewall Configuration)

------------------------------------------------

실습 준비

모든 서비스 차단

telnet 서비스 허용

rlogin 서비스 허용

SSH 서비스 허용

ICMP 서비스 허용

WEB 서비스 허용

NFS 서비스 허용

NTP 서비스 허용

DNS 서비스 허용

FTP 서비스 허용

MAIL, POP3, IMAP 서비스 허용

------------------------------------------------

 

 

 

 

(가정) 다음 사항을 가정한다.

CentOS 5.4/CentOS 5.8/CentOS 5.9/CentOS 5.10/CentOS 5.11 환경에서 테스트 한다.

모든 서버에 최신의 패치(# yum -y update)가 적용되어 있는 것으로 가정한다.# yum check-update (check-update Check for available package updates)# yum -y update -> 커널 업데이트가 들어 있는 경우(# yum check-update | grep kernel)# reboot

 

 

[EX1] 실습 준비

 

Firewall(iptables)

Linux(KaliLinux) <----------> Linux(firwall) <----------> Linux(linux200)

192.168.10.50 192.168.10.100 192.168.20.100 192.168.20.200

Windows(win2008)

192.168.20.201

 

[그림] 실습 환경

 

 

방화벽 서버와 통신 가능 확인

모든 서버에 nmap(Port Scanning) 프로그램 설치

 

 

 

(192.168.20.200) linux200

서버가 통신 가능한 상태인지 ping 명령어를 통해 확인

대표적인 서비스 몇가지, telnet, ftp, 서비스가 서버와 통신이 가능한지 확인한다.

 

서버와 통신 가능 확인(ping)

# ping -c 2 192.168.20.100

PING 192.168.20.100 (192.168.20.100) 56(84) bytes of data.

64 bytes from 192.168.20.100: icmp_seq=1 ttl=64 time=0.951 ms

64 bytes from 192.168.20.100: icmp_seq=2 ttl=64 time=0.532 ms

 

--- 192.168.20.100 ping statistics ---

2 packets transmitted, 2 received, 0% packet loss, time 1001ms

rtt min/avg/max/mdev = 0.532/0.741/0.951/0.211 ms

 

 

 

서버와 통신 가능 확인(telnet)

 

[참고] 필요하면 설정

(firewall) 192.168.20.100

# chkconfig krb5-telnet on

# service xinetd restart

# for i in `seq 1 11`

do

echo "pts/$i" >> /etc/securetty

done

 

(linux200 --- telnet ---> firewall)

# telnet 192.168.20.100

Trying 192.168.10.2XX...

Connected to 192.168.10.2XX (192.168.10.2XX).

Escape character is '^]'.

 

linux2XX (Linux release 2.6.18-164.15.1.el5 #1 SMP Wed Mar 17 11:37:14 EDT 2010) (3)

 

login: root

Password: (soldesk1.)

Last login: Tue Mar 30 02:24:00 from 192.168.10.1XX

# <CTRL + D>

 

서버와 통신 가능 확인(ftp)

 

[참고] 필요하면 설정

(firewall) 192.168.20.100

# chkconfig vsftpd on

# service vsftpd restart

# sed -i 's/^root/#root/' /etc/vsftpd/ftpusers

# sed -i 's/^root/#root/' /etc/vsftpd/user_list

 

(linux200 --- ftp ---> firewall)

# ftp 192.168.20.100

Connected to 192.168.20.100.

220 (vsFTPd 2.0.5)

530 Please login with USER and PASS.

530 Please login with USER and PASS.

KERBEROS_V4 rejected as an authentication type

Name (192.168.20.100:root): root

331 Please specify the password.

Password: (root 사용자 암호 입력)

230 Login successful.

Remote system type is UNIX.

Using binary mode to transfer files.

ftp> quit

221 Goodbye.

 

서버의 열린 포트 확인

 

[참고] 필요하면 명령어 수행

# vi /etc/resolv.conf

nameserver 168.126.63.1

nameserver 172.16.9.2XX

# yum -y install nmap

 

(linux200 --- nmap ---> firewall)

# nmap 192.168.20.100

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-09 16:57 KST

Interesting ports on nic2 (192.168.20.100):

Not shown: 1674 closed ports

PORT STATE SERVICE

21/tcp open ftp

22/tcp open ssh

23/tcp open telnet

37/tcp open time

111/tcp open rpcbind

643/tcp open unknown

MAC Address: 00:0C:29:A2:83:8F (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 0.230 seconds

 

[참고] 포트번호의 정의(IANA)

- http://www.iana.org/assignments/port-numbers

- /etc/services 파일

[EX2] 모든 서비스 차단

 

(192.168.20.100) Firewall

 

(선수작업) 별도의 스크립트를 사용하기 위해서 iptables 서비스는 off 시킨다.

# chkconfig iptables off

# chkconfig --list iptables

 

# mkdir -p /root/bin

# vi /root/bin/iptables.sh

#!/bin/bash

 

iptables -F -t filter

iptables -F -t nat

 

#

# (1) Local ACCEPT

#

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

 

#

# (2) Policy

#

 

#

# (3) All DROP

#

iptables -P INPUT DROP

 

Statefull TrackingUsing stateful rules reduces rule set complexity and increses security

-m state --state ESTABLEISHED,RELATED

state

This module, when combined with connection tracking, allows access

to the connection tracking state for this packet.

 

--state state

Where state is a comma separated list of the connection

states to match. Possible states are INVALID meaning that

the packet could not be identified for some reason which

includes running out of memory and ICMP errors which don't

correspond to any known connection, ESTABLISHED meaning that

the packet is associated with a connection which has seen

packets in both directions, NEW meaning that the packet has

started a new connection, or otherwise associated with a

connection which has not seen packets in both directions,

and RELATED meaning that the packet is starting a new con-

nection, but is associated with an existing connection, such

as an FTP data transfer, or an ICMP error.

 

# chmod 755 /root/bin/iptables.sh

# /root/bin/iptables.sh

# iptables -L

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

 

 

(192.168.20.200) linux200

 

(linux200 --- ping ---> firewall)

# time ping -c 1 192.168.20.100

PING 192.168.20.100 (192.168.20.100) 56(84) bytes of data.

 

--- 192.168.20.100 ping statistics ---

1 packets transmitted, 0 received, 100% packet loss, time 0ms

 

 

real 0m10.044s

user 0m0.005s

sys 0m0.032s

 

(linux200 --- nmap ---> firewall)

# time nmap 192.168.20.100

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-09 17:24 KST

All 1680 scanned ports on nic2 (192.168.20.100) are filtered

MAC Address: 00:0C:29:A2:83:8F (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 35.242 seconds

 

real 0m35.251s

user 0m0.077s

sys 0m0.006s

 

 

 

 

 

 

[EX3] telnet 서비스 제어

 

 


 

 

 

 

 

 

(192.168.20.100) Firewall

 

telnet 서비스를 open 하기 위한 설정을 한다.

tenlet 서비스용 서버 포트는 23(TCP)를 사용하고 있다.

telnet 서비스는 암호화 방식을 택하지 않고 평문 형태의 패킷으로 통신하게 된다. 따라서 telnet 서버스를 반드시 사용해야 한다면 특정한 PC만 서버에 접속할 수 있도록 설정해야 한다.

 

# vi /root/bin/iptables.sh

#!/bin/ksh

 

iptables -F

iptables -F -t nat

 

#

# (1) Local ACCEPT

#

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

 

#

# (2) Policy

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.20.200 -d 192.168.20.100 --dport 23 -j ACCEPT

 

#

# (3) All DROP

#

iptables -P INPUT DROP

 

# /root/bin/iptables.sh

# iptables -L (# service iptables status)

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- 192.168.20.200 nic2 state NEW tcp dpt:telnet

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

(192.168.20.200) linux200

 

# telnet 192.168.20.100

Trying 192.168.20.100...

Connected to nic2 (192.168.20.100).

Escape character is '^]'.

 

firewall.example.com (Linux release 2.6.18-371.12.1.el5 #1 SMP Wed Sep 3 16:22:56 EDT 2014) (1)

 

login: root

Password: (root 사용자의 암호 입력)

Last login: Tue Mar 30 03:30:11 from 192.168.10.1XX

You have new mail.

 

# exit

#

 

# time nmap 192.168.20.100

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-09 17:31 KST

Interesting ports on nic2 (192.168.20.100):

Not shown: 1679 filtered ports

PORT STATE SERVICE

23/tcp open telnet

MAC Address: 00:0C:29:A2:83:8F (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 22.043 seconds

 

real 0m22.051s

user 0m0.076s

sys 0m0.013s

 

 

[참고] 다른 호스트 쪽에서 telnet 서비스를 192.168.10.2XX 서버쪽으로 테스트해 본다.

(KaliLinux) 192.168.10.50

# telnet 192.168.10.100

# nmap 192.168.10.100

(Windows2008) 192.168.20.201

Putty 사용해서 telnet 해 본다.(192.168.20.201 -> 192.168.20.100)

필요하면 Windows nmap으로 확인 해 본다.

 

 

 

 

 

 

[EX4] SSH 서비스 제어

 


 

 

 

192.168.20.0/24 네트워크에서 ssh 명령어 접속을 할 수 있도록 설정한다.

ssh 서비스는 데이터를 전송할 때 암호화 하므로 서버와 같은 네트워크를 사용하고 있는 경우 모두에게 서비스가 가능하도록 설정한다.

SSH 서비스용 서버 포트는 22(ssh, sftp, scp, TCP)을 사용한다.

 

 

 

 

 

(192.168.20.100) Firewall

 

# vi /root/bin/iptables.sh

#!/bin/ksh

 

iptables -F

iptables -F -t nat

 

#

# (1) Local ACCEPT

#

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

 

#

# (2) Policy

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.20.200 -d 192.168.20.100 --dport 23 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.20.0/24 -d 192.168.20.100 --dport 22 -j ACCEPT

 

#

# (3) All DROP

#

iptables -P INPUT DROP

 

[참고] 필요하면 명령어 수행

# alias a='vi /root/bin/iptables.sh'

# alias b='/root/bin/iptables.sh'

# alias c='iptables -L'

 

# /root/bin/iptables.sh

# iptables -L (# service iptables status)

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- 192.168.20.200 nic2 state NEW tcp dpt:telnet

ACCEPT tcp -- 192.168.20.0/24 nic2 state NEW tcp dpt:ssh

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

 

 

(192.168.20.200) linux200

 

# ssh 192.168.20.100

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

RSA key fingerprint is c6:d1:9a:14:84:6c:1b:df:4d:b0:3b:53:b5:1f:7a:73.

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

Warning: Permanently added '192.168.20.100' (RSA) to the list of known hosts.

root@192.168.20.100's password: (soldesk1.)

Last login: Tue Dec 9 17:30:05 2014 from 192.168.20.200

 

# exit

#

 

# nmap 192.168.20.100

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-09 17:42 KST

Interesting ports on nic2 (192.168.20.100):

Not shown: 1678 filtered ports

PORT STATE SERVICE

22/tcp open ssh

23/tcp open telnet

MAC Address: 00:0C:29:A2:83:8F (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 21.212 seconds

 

 

[참고] 다른 호스트 쪽에서 ssh 서비스를 linux2XX 서버쪽으로 테스트해 본다.

(KaliLinux)

# ssh 192.168.10.100

# nmap 192.168.10.100

(Windows2008)

Putty 사용해서 ssh 해 본다.(192.168.20.201 -> 192.168.20.100)

필요하면 Windows nmap으로 확인 해 본다.

 

 




[EX5] ICMP 서비스 허용/차단

 


 

 

 

 

 

 

(192.168.20.100) Firewall

 

# vi /root/bin/iptables.sh

#!/bin/ksh

 

iptables -F

iptables -F -t nat

 

#

# (1) Local ACCEPT

#

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

 

#

# (2) Policy

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.20.200 -d 192.168.20.100 --dport 23 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.20.0/24 -d 192.168.20.100 --dport 22 -j ACCEPT

iptables -A OUTPUT -p icmp --icmp-type echo-request -s 192.168.20.100 -d 0/0 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -d 192.168.20.100 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type destination-unreachable -s 0/0 -d 192.168.20.100 -j ACCEPT

 

#

# (3) All DROP

#

iptables -P INPUT DROP

 

 

 

[참고] iptables -p icmp -h

# iptables -p icmp h

iptables v1.3.5

 

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

 

Valid ICMP Types:

any

echo-reply (pong)

destination-unreachable

network-unreachable

host-unreachable

protocol-unreachable

port-unreachable

fragmentation-needed

source-route-failed

network-unknown

host-unknown

network-prohibited

host-prohibited

TOS-network-unreachable

TOS-host-unreachable

communication-prohibited

host-precedence-violation

precedence-cutoff

source-quench

redirect

network-redirect

host-redirect

TOS-network-redirect

TOS-host-redirect

echo-request (ping)

router-advertisement

router-solicitation

time-exceeded (ttl-exceeded)

ttl-zero-during-transit

ttl-zero-during-reassembly

parameter-problem

ip-header-bad

required-option-missing

timestamp-request

timestamp-reply

address-mask-request

address-mask-reply

 

 

 

 

# /root/bin/iptables.sh

# iptables -L (# service iptables status)

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- 192.168.20.200 nic2 state NEW tcp dpt:telnet

ACCEPT tcp -- 192.168.20.0/24 nic2 state NEW tcp dpt:ssh

ACCEPT icmp -- nic2 anywhere icmp echo-request

ACCEPT icmp -- anywhere nic2 icmp echo-reply

ACCEPT icmp -- anywhere nic2 icmp destination-unreachable

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

# ping -c 2 192.168.20.200

PING 192.168.10.1XX (192.168.10.1XX) 56(84) bytes of data.

64 bytes from 192.168.10.1XX: icmp_seq=1 ttl=64 time=1.12 ms

64 bytes from 192.168.10.1XX: icmp_seq=2 ttl=64 time=1.03 ms

 

--- 192.168.10.1XX ping statistics ---

2 packets transmitted, 2 received, 0% packet loss, time 1523ms

rtt min/avg/max/mdev = 1.030/1.077/1.125/0.057 ms

 

 

 

 

(192.168.20.200) linux200

 

# ping -c 1 192.168.20.100

PING 192.168.10.2XX (192.168.10.2XX) 56(84) bytes of data.

 

--- 192.168.10.2XX ping statistics ---

1 packets transmitted, 0 received, 100% packet loss, time 0ms

 

 

 

 

 

 



[EX6] WEB 서비스 허용

 


 

 

 

 

WEB(80, TCP)

 

 

(192.168.20.100) Firewall

 

# vi /root/bin/iptables.sh

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

#

# (2) Policy

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.1XX -d 192.168.10.2XX --dport 23 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.0/24 -d 192.168.10.2XX --dport 22 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-request -s 192.168.10.2XX -d 0/0 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -d 192.168.10.2XX -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 0/0 -d 192.168.20.100 --dport 80 -j ACCEPT

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

 

# /root/bin/iptables.sh

# iptables -L (# service iptables status)

Chain INPUT (policy DROP)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- 192.168.20.200 nic2 state NEW tcp dpt:telnet

ACCEPT tcp -- 192.168.20.0/24 nic2 state NEW tcp dpt:ssh

ACCEPT icmp -- nic2 anywhere icmp echo-request

ACCEPT icmp -- anywhere nic2 icmp echo-reply

ACCEPT icmp -- anywhere nic2 icmp destination-unreachable

ACCEPT tcp -- anywhere nic2 state NEW tcp dpt:http

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

# rpm -qa | grep httpd

httpd-2.2.3-87.el5.centos

httpd-manual-2.2.3-87.el5.centos

system-config-httpd-1.3.3.3-1.el5

 

# cd /var/www/html

# vi index.html

<H1><CENTER> firewall.example.com </CENTER></H1>

 

# service httpd restart

Stopping httpd: [ OK ]

Starting httpd: [ OK ]

 

 

 

(192.168.20.200) linux200

 

# lynx http://192.168.20.100/ (# firefox http://192.168.20.100)

-> 웹페이가 보여야 한다.

-> # telnet 192.168.20.100 80

GET

 

# nmap 192.168.20.100

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-12-09 18:17 KST

Interesting ports on nic2 (192.168.20.100):

Not shown: 1677 filtered ports

PORT STATE SERVICE

22/tcp open ssh

23/tcp open telnet

80/tcp open http

MAC Address: 00:0C:29:A2:83:8F (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 20.392 seconds

 

[참고] 다른 호스트 쪽에서 ssh 서비스를 linux2XX 서버쪽으로 테스트해 본다.

(KaliLinux)

# telnet 192.168.10.100 80

GET

# nmap 192.168.10.100

(Windows2008)

c:> telnet 192.168.20.100 80

GET

필요하면 Windows nmap으로 확인 해 본다.

 

 

 

 

 

 

[EX8] NFS 서비스 허용

 


 

 

 

 

 

# rpcinfo -t linux2XX.example.com nfs

program 100003 version 2 ready and waiting

program 100003 version 3 ready and waiting

program 100003 version 4 ready and waiting

 

# rpcinfo -u linux2XX.example.com nfs

program 100003 version 2 ready and waiting

program 100003 version 3 ready and waiting

program 100003 version 4 ready and waiting

 

(1) NFSv2/NFSv3 서비스의 동작 원리

 

----- NFS Server ------ ----- NFS Client -----

rpc.mountd rpc.statd

rpc.nfsd rpc.lockd

rpc.rquotad

rpc.statd

rpc.lockd

 

# vi /etc/exports # mkdir /p

# exportfs -ar # mount.nfs4 SERVER:/share /p

 

 

 

(2) NFSv4 서비스의 동작 원리

 

 

 

 

 

 

 

 

[참고] NFSv4 서버/클라이언트 설정 방법

http://blog.laimbock.com/2009/05/21/nfsv4-on-centos-53-and-fedora-11/http://blog.laimbock.com/2009/05/21/nfsv4-on-centos-53-and-fedora-11/

(192.168.10.2XX) Firewall Server (linux2XX)

 

# vi /root/bin/iptables.sh

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

#

# (2) Policy

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.1XX -d 192.168.10.2XX --dport 23 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.0/24 -d 192.168.10.2XX --dport 22 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-request -s 192.168.10.2XX -d 0/0 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -d 192.168.10.2XX -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 0/0 -d 192.168.10.2XX --dport 80 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.1XX -d 192.168.10.2XX --dport 2049 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.1XX -d 192.168.10.2XX --dport 111 -j ACCEPT

iptables -A INPUT -m state --state NEW -p udp -s 192.168.10.1XX -d 192.168.10.2XX --dport 111 -j ACCEPT

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

-> rpcbind(111) 포트를 반드시 Open 필요는 없다.

-> NFSv4(nfsd) 서비스는 2049번 단일 포트를 사용하고, 단일 프로토콜 TCP를 사용한다.

 

# /root/bin/iptables.sh

# service iptables status (# iptables -L)

Table: filter

Chain INPUT (policy DROP)

num target prot opt source destination

1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0

2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED

3 ACCEPT tcp -- 192.168.10.1XX 192.168.10.2XX state NEW tcp dpt:23

4 ACCEPT tcp -- 192.168.10.0/24 192.168.10.2XX state NEW tcp dpt:22

5 ACCEPT icmp -- 192.168.10.2XX 0.0.0.0/0 icmp type 8

6 ACCEPT icmp -- 0.0.0.0/0 192.168.10.2XX icmp type 0

7 ACCEPT tcp -- 0.0.0.0/0 192.168.10.2XX state NEW tcp dpt:80

8 ACCEPT tcp -- 192.168.10.1XX 192.168.10.2XX state NEW tcp dpt:2049

9 ACCEPT tcp -- 192.168.10.1XX 192.168.10.2XX state NEW tcp dpt:111

10 ACCEPT udp -- 192.168.10.1XX 192.168.10.2XX state NEW udp dpt:111

 

Chain FORWARD (policy ACCEPT)

num target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

num target prot opt source destination

 

# vi /etc/exports

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

/export/centos *(ro,no_root_squash)

 

# service nfs restart

-> 출력 내용 생략

 

# exportfs -v

/export/centos <world>(ro,wdelay,no_root_squash,no_subtree_check,anonuid=65534,anongid=65534)

 

 

(192.168.10.1XX) Client (linux1XX)

# mkdir p /mnt/server

# mount 192.168.10.2XX:/export/centos /mnt/server

# df h /mnt/server

# ls /mnt/server

 

# nmap -sT 192.168.10.2XX

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-09-02 15:23 KST

Interesting ports on 192.168.10.250:

Not shown: 1676 filtered ports

PORT STATE SERVICE

22/tcp open ssh

23/tcp open telnet

80/tcp open http

111/tcp open rpcbind

2049/tcp open nfs

MAC Address: 00:0C:29:88:90:CB (VMware)

 

Nmap finished: 1 IP address (1 host up) scanned in 33.227 seconds

-> 포트번호를 검색한다.

-> 원격 자원 마우트를 시도해 본다.

[참고] system-config-securitylevel 툴을 통해 설정한 내용(선택할 수 있는 모든 서비스 허용)

 

(TUI) # system-config-securitylevel-tui (# lokkit)

(GUI) # system-config-securitylevel

 

# iptables -F

# iptables -P INPUT ACCEPT (# service iptables stop)

# iptables -L

-> 특별한 설정이 없는 상태

 

# system-config-securitylevel &

--------------------------------------------------

Firewall: Enabled

Trusted services: [ V ] FTP

[ V ] Mail (SMTP)

[ V ] NFSv4

[ V ] SSH

[ V ] Samba

[ V ] Secure WWW (HTTPS)

[ V ] Telnet

[ V ] WWW (HTTP)

--------------------------------------------------

 

# iptables -L

Chain INPUT (policy ACCEPT)

target prot opt source destination

RH-Firewall-1-INPUT all -- anywhere anywhere

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

RH-Firewall-1-INPUT all -- anywhere anywhere

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

Chain RH-Firewall-1-INPUT (2 references)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT icmp -- anywhere anywhere icmp any

ACCEPT esp -- anywhere anywhere

ACCEPT ah -- anywhere anywhere

ACCEPT udp -- anywhere 224.0.0.251 udp dpt:mdns

ACCEPT udp -- anywhere anywhere udp dpt:ipp

ACCEPT tcp -- anywhere anywhere tcp dpt:ipp

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ftp

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:smtp

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:nfs

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh

ACCEPT udp -- anywhere anywhere state NEW udp dpt:netbios-ns

ACCEPT udp -- anywhere anywhere state NEW udp dpt:netbios-dgm

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:netbios-ssn

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:microsoft-ds

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:https

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:telnet

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:http

ACCEPT udp -- anywhere anywhere state NEW udp dpt:domain

REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

 

or

 

Chain INPUT (policy ACCEPT)

target prot opt source destination

RH-Firewall-1-INPUT all -- anywhere anywhere

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

RH-Firewall-1-INPUT all -- anywhere anywhere

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

 

Chain RH-Firewall-1-INPUT (2 references)

target prot opt source destination

ACCEPT all -- anywhere anywhere

ACCEPT icmp -- anywhere anywhere icmp any

ACCEPT esp -- anywhere anywhere

ACCEPT ah -- anywhere anywhere

ACCEPT udp -- anywhere 224.0.0.251 udp dpt:mdns

ACCEPT udp -- anywhere anywhere udp dpt:ipp

ACCEPT tcp -- anywhere anywhere tcp dpt:ipp

ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ftp

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:smtp

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:nfs

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh

ACCEPT udp -- anywhere anywhere state NEW udp dpt:netbios-ns

ACCEPT udp -- anywhere anywhere state NEW udp dpt:netbios-dgm

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:netbios-ssn

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:microsoft-ds

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:https

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:telnet

ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:http

REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

 

# cat /etc/sysconfig/iptables

-> 내용 확인

 

# chkconfig --list iptables

-> 설정 정보 확인

 

 

 

 

 

 


[참고] 각 서비스들에 대한 제어 예제

(주의) 반드시 source ip 부분이나 destination ip 부분의 지정이 필요하다.

 

(WEB) HTTP -- TCP 80

iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

 

(WEB) HTTPS -- TCP 443

iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

iptables -A INPUT -m state --state NEW -m tcp -p tcp -m multiport --dports 80,443 -j ACCEPT

 

(DB) MySQL -- TCP 3306

iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

 

(FTP) active mode -- TCP 21,20

iptables -A INPUT -p tcp --dport 21 -j ACCEPT

iptables -A INPUT -p tcp --dport 20 -j ACCEPT

 

(FTP) passive mode -- TCP 21, 1024-65535

iptables -A INPUT -p tcp --dport 21 -j ACCEPT

iptables -A INPUT -p tcp --dport 1024:65535 -j ACCEPT

 

(MAIL) SMTP -- TCP 25

iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT

 

(MAIL) Secure SMTP -- TCP 465

iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT

 

(MAIL) POP3 -- TCP 110

iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT

 

(MAIl) Secure POP3 -- TCP 995

iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT

 

(MAIl) IMAP -- TCP 143

iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT

 

(MAIl) Secure IMAP -- 993

iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT

 

(ICMP) ICMP 허용 (ping)

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

 

(NTP) -- UDP 123

iptables -A INPUT -p udp --dport 123 -j ACCEPT

 

(DHCP) -- UDP 67,68

iptables -A INPUT -p udp --dport 67:68 j ACCEPT

 

(SAMBA) -- TCP 445, 137,138,139

iptables -A INPUT -m state --state NEW -p tcp --dport 445 j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp --dport 137:139 j ACCEPT

 

 

 

 

 

 

 

[참고] 서버 취약점 보안에 대한 예제(EX: 홈게이트웨이, 홈라우터 설정시 참고)

 

(참고)

# sysctl -a

# cat /etc/sysctl.conf

 

커널 패러미터 변경하는 작업 방법

# vi /etc/sysctl.conf

net.ipv4.ip_forward = 1

# sysctl -p

or

# sysctl -w net.ipv4.ip_forward=1

# sysctl -p

or

# echo 1 > /proc/sys/net/ipv4/ip_forward

# vi /etc/sysctl.conf

net.ipv4.ip_forward = 1

 

커널 패러미터 관련 정보

/proc/sys/net/ipv4/ip_forward

-> net.ipv4.ip_forward

 

man sysctl

man sysctl.conf

 

NULL 패킷 차단 ---> (Scanning) TCP NULL Scan

NULL 패킷은 정찰(Scanning) 패킷으로 서버설정의 약한 곳(Port scan)을 찾기위한 방법으로 사용된다.

# iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

 

syn-flood attack 차단 ---> (DoS/DDoS) DoS Attack

syn-flood attack은 공격자가 새로운 연결을 만들고 빠지고를 반복해 리소스의 소모를 시킨다.

# iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

 

Anti synflood with iptables

 

Edit /etc/sysctl.conf to defend against certain types of attacks and append / update as follows:

 

net.ipv4.tcp_syncookies = 1

net.ipv4.conf.all.rp_filter = 1

net.ipv4.conf.default.rp_filter = 1

net.ipv4.tcp_max_syn_backlog = 8192

net.ipv4.netfilter.ip_conntrack_max = 1048576

 

XMAS 패킷 차단 ---> (Scanning) TCP Xmas Scan

XMAS 또한 정찰(Scanning) 패킷

# iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

 

MAC 주소로 제어

신뢰할 만한 ipMAC주소에 대해 모든 패킷을 허용

# iptables -A INPUT -s 192.168.0.3 -m mac --mac-source 00:50:80:FD:E6:32 -j ACCEPT

 

IP 주소로 제어

신뢰할 만한 ip에 대해 모든 패킷을 허용

# iptables -A INPUT -s 192.168.0.3 -j ACCEPT

 

신뢰할 만한 ip 대역에 대해 모든 패킷을 허용

# iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT

 

신뢰할 만한 ip 대역에 대해 모든 패킷을 허용

# iptables -A INPUT -s 192.168.0.0/255.255.255.0 -j ACCEPT

 

포트 주소 범위로 지정

# iptables -A INPUT -p tcp --dport 6881:6890 -j ACCEPT

 

 

 

 

 

[참고] NAT(Network Address Translation) 대해서

[참고] http://blog.beany.co.kr/archives/2157

 

NAT 종류(Network 구분하는 경우)

* Normal NAT (사설 IP -> 공인 IP)

* Reverse NAT (공인 IP -> 사설 IP)

* Exclude NAT (NAT 적용하지 않는 host/Network 지정)

* Redirect NAT (특정 시스템으로 지정한 서비스 Forwarding)

 

NAT 종류(Network 구분하는 경우) 공인 IP 몇개를 물릴것인가?, 사설 IP가 고정되어 있는가?

* Dynamic NAT(N:1 or N:M)

여러개의 사설 IP : (여러개) 공인 IP

* Static NAT (1:1)

사설 IP : 공인 IP

 

NAT 종류(Network/Server 구분하는 경우) 어떤 주소(소스 주소/목적 주소)가 변경되는가?

* SNAT(Source NAT) : Source IP 주소 변경 (EX : 마스커레이딩)

* DNAT(Destination NAT) : Destination IP 주소 변경 (EX : Port Forwarding)

 

 

SNAT & DNAT

 

-i eth0 -o eth0

PREROUTING --> 라우팅 ----------------->POSTROUTING----->

 (D-NAT)           |                         (S-NAT)

                         |                            ^

                         |                            |

                         +-------> 로컬 프로세스 -----+

 

- Table(EX: NAT) -> Chain(EX: PREROUTING, POSTROUTING, OUTPUT) -> Rules

- PREROUTING(DNAT 경우, 패킷이 들어올때)

- POSTROUTING(SNAT 경우, 패킷이 나갈때)

 

 

 

SNAT 설정의 예

소스의 주소를 1.2.3.4로 변경하는 예

# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4

 

소스의 주소를 1.2.3.4 ~ 1.2.3.6로 변경하는 예

# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4-1.2.3.6

 

소스의 주소 1.2.3.4에 포트 1-1023로 변경하는 예

# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4:1-1023

 

마스쿼레이딩 설정(SNAT 방식의 특이한 경우)

# iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE (N:1 방식, 유동IP/고정IP)

-> SNAT는 주로 고정 IP 방식에서 사용(eth0 : 회사가 보유한 고정/공인 IP)

-> DNAT는 주로 유동 IP 방식에서 사용(ppp0 : 통신 회사가 제공하는 유동/공인 IP)

 

DNAT 설정의 예

목적지 주소를 1.2.3.4로 변경하는 경우

# iptables -t nat -A PREROUTING -i eth1 -j DNAT --to 1.2.3.4

 

목적지 주소를 1.2.3.4 ~ 1.2.3.6로 변경하는 경우(부하 분산하는 경우)

# iptables -t nat -A PREROUTING -i eth1 -j DNAT --to 1.2.3.4-1.2.3.6

 

웹 트래픽에 대한 목적지 주소를 1.2.3.48080 포트로 변경하는 경우

# itpables -t nat -A PREROUTING -p tcp --dport 80 -i eth1 -j DNAT --to 1.2.3.4:8080

 

1.2.3.4 목적지 주소로 가는 지역 패킷을 loopback으로 재설정 하기

# iptables -t nat -A OUTPUT -d 1.2.3.4 -j DNAT --to 127.0.0.1

 

방향재설정(Redirect) - Local Port Forwarding

# iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 3128

DNAT 종류 중 예제 - Remote Port Forwarding

# iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j DNAT --to 1.2.3.4:8080

 

----------------------------------------------------------------------------------------

MASQERADE 설정

# iptables -t nat -A POSTROUTING -o eth0 -j MASQERADE

 

Network interface(eth0)을 통한 Port Forwarding

# iptables -t nat -A PREROUTING -p tcp -i eth0 --dport ${port} -j DNAT --to ${IP:Port}

 

특정 IP를 통한 Port Forwarding

# iptables -t nat -A PREROUTING -p tcp -d ${IP} -j DNAT --to-destination ${IP:Port}

 

Local Port Forwarding

# iptables -t nat -A PREROUTING -p tcp -d ${IP} --dport ${Port} -j REDIRECT --to-port ${Port}

----------------------------------------------------------------------------------------

 

 

 

 

[참고] 방화벽 스크립트 만들기 예제(EX: 수업에서 사용한 명령어들의 묶음)

/root/bin/iptables.sh 스크립트

 

# cat /root/bin/iptables.sh

#!/bin/bash

 

iptables -F

iptables -F -t nat

 

#

# (1) Local ACCEPT

#

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

 

#

# (2) Policy

#

 

#

# (2-1) TELNET Service

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.149 -d 192.168.10.249 --dport 23 -j ACCEPT

#

# (2-2) SSH Service

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.0/24 -d 192.168.10.249 --dport 22 -j ACCEPT

#

# (2-3) ICMP Service

#

iptables -A INPUT -p icmp --icmp-type echo-request -s 192.168.10.249 -d 0/0 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-reply -s 0/0 -d 192.168.10.249 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type destination-unreachable -s 0/0 -d 192.168.10.249 -j ACCEPT

#

# (2-4) WEB Service

#

iptables -A INPUT -m state --state NEW -p tcp -s 0/0 -d 0/0 --dport 80 -j ACCEPT

#

# (2-5) NFSv4 Service

#

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.149 -d 192.168.10.249 --dport 2049 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp -s 192.168.10.149 -d 192.168.10.249 --dport 111 -j ACCEPT

iptables -A INPUT -m state --state NEW -p udp -s 192.168.10.149 -d 192.168.10.249 --dport 111 -j ACCEPT

#

# (2-6) MAIL/POP3/IMAP4 Service

#

iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT

iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT

#

# (2-7) DNS Service

#

iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT

#

# (2-8) FTP Service

#

iptables -A INPUT -m state --state NEW -p tcp --dport 21 -A ACCEPT

 

#

# (3) All DROP

#

iptables -P INPUT DROP

 

 

 

(1) 서버 - 서비스(EX: 웹서버)

- 웹서비스(80)

- 원격접속 SSH(22)

- 파일전송 SFTP(22)

- ping(ICMP)

(2) 성능 이슈 - 서비스(EX: 웹서버)

- rules 개수를 줄일수 있는가?

- 주 서비스(EX: 웹서비스) rules은 가장 상단에 위치

 

 


[참고] 방화벽 스크립트 만들기 예제(EX: 실제 방화벽 스크립트 실무)

/root/bin/iptables.sh 스크립트(우분트 기준)

 

# cat /root/bin/iptables.sh

#!/bin/bash

 

## 현재 스크립트가 루트/sudo 권한으로 실행중인지 체크하고 그렇지 않을 경우 에러 메세지를 표시합니다.

echo [*] Checking if run on the root...

if [ `whoami` != root ]; then

echo [!] Error : Please run this script as root or using sudo!!

exit 1

fi

 

echo [*] Setting Up IPTABLES Rules...

 

echo [*] Applying Variables...

OUTTER_INT=eth0

INNER_INT=eth1

INNER_NET=192.168.10.0/24

 

## 외부 IP 주소를 얻어옵니다. (이유는 NAT 정책에 설명해 놓은 글을 참고하시기 바랍니다.)

## ifconfig 출력 화면을 활용하여 현재 외부망으로 연결되어있는 인터페이스로 부터 외부 IP 주소를 얻어옵니다.

## 현재 IP주소는 root 계정의 홈폴더에 myip 라는 파일에 저장됩니다.

echo [*] Getting current ip address from Outter Interface...

ifconfig $OUTTER_INT > $HOME/myip.tmp1

sed "s/Bcast:/\n/" < $HOME/myip.tmp1 > $HOME/myip.tmp2

head -2 $HOME/myip.tmp2 | tail -1 > $HOME/myip.tmp3

sed "s/ \ \ \ \ \ \ \ \ \ inet\ addr://" < $HOME/myip.tmp3 > $HOME/myip

rm -rf $HOME/myip.tmp*

IP=$(cat $HOME/myip)

 

 

## 현재 iptables에 설정 되어 있는 항목들을 지웁니다.

echo [*] Flushing current iptables rules...

### Flush ###

iptables -F

iptables -F -t nat

iptables -X

## FTP Passive 모드 작동을 위한 모듈이 로드되어 있을 경우 해제합니다.

modprobe -r ip_conntrack_ftp

## iptables 기본 정책들을 DROP으로 설정합니다. 이로써 허용한 패킷들 외에는 모두 차단됩니다.

echo [*] Changing default policy to DROP...

iptables -P INPUT DROP

iptables -P OUTPUT DROP

iptables -P FORWARD DROP

 

 

 

## INPUT 정책을 설정합니다.

echo [*] Applying INPUT rules...

### INPUT ###

## Check Packets

## 들어온 패킷이 정상적으로 연결을 맺은 패킷이 아닐경우 차단합니다.

iptables -A INPUT -m state --state INVALID -j DROP

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

## Anti Spoofing

## 내부 주소로 부터 IP 스푸핑이 되는 것을 방지합니다.

iptables -A INPUT -i $INNER_INT ! -s $INNER_NET -j DROP

## Accept

## 외부와 통신하기 위한 포트 번호들을 설정합니다.

## 다른 포트 번호 추가시 -p tcp 또는 -p udp 를 지정한 후 --sport 뒤의 포트 번호를 수정하여 추가해주시면 됩니다.

## 1443은 금융사이트 이용시 TouchEn key 라는 키보드 보안 프로그램을 위한 포트번호입니다. 해당 포트 번호가 차단되어 있을 경우 금융사이트를 원활히 이용하실 수 없습니다.

## 각 포트 번호들에 설명은 Forward 정책에 표시해 뒀으니 참고하시기 바랍니다.

iptables -A INPUT -p tcp ! -s $IP --sport 20 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 21 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 80 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 443 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 465 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 993 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

iptables -A INPUT -p tcp ! -s $IP --sport 1443 -d $IP --dport 1024:65535 --syn -m state --state NEW -j ACCEPT

 

iptables -A INPUT -p udp ! -s $IP --sport 53 -d $IP --dport 1024:65535 -m state --state NEW -j ACCEPT

iptables -A INPUT -p udp ! -s $IP --sport 123 -d $IP --dport 1024:65535 -m state --state NEW -j ACCEPT

 

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT # from other to here

iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT # from here to other

 

 

## OUTPUT 정책을 설정합니다. 기본 구조는 INPUT과 비슷하나 출발지와 목적지만 반대로 되어있다고 보시면 됩니다.

## 포트번호 추가시 INPUT 정책과 비슷한 방식으로 ACCEPT 부분에 -p tcp 또는 -p udp 지정 후 --dport 뒤의 포트 번호를 수정하여 추가해 주시면 됩니다.

echo [*] Applying OUTPUT rules...

### OUTPUT ###

## Check Packets

iptables -A OUTPUT -m state --state INVALID -j DROP

iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

## ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 20 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 21 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 80 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 443 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 465 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 993 --syn -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p tcp -s $IP --sport 1024:65535 ! -d $IP --dport 1443 --syn -m state --state NEW -j ACCEPT

 

iptables -A OUTPUT -p udp -s $IP --sport 1024:65535 ! -d $IP --dport 53 -m state --state NEW -j ACCEPT

iptables -A OUTPUT -p udp -s $IP --sport 1024:65535 ! -d $IP --dport 123 -m state --state NEW -j ACCEPT

 

iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT # from other to here

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT # from here to other

 

 

## FTP Passive 모드와 통신하기 위한 모듈을 로드합니다.

echo [*] Loading FTP Passive Connection Tracking Module...

### Load FTP Passive Connection Tracking Module ###

modprobe ip_conntrack_ftp

 

## Forward 정책을 설정합니다.

## 마찬가지로 포트번호 추가시 ACCEPT 부분에 -p tcp 또는 -p udp 지정 후 --dport 뒤의 포트 번호를 수정하여 추가해 주시면 됩니다.

echo [*] Applying Forward rules...

### Forward ###

## Check Packets

iptables -A FORWARD -m state --state INVALID -j DROP

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

## Anti Spoofing

iptables -A FORWARD -i $INNER_INT ! -s $INNER_NET -j DROP

## ACCEPT

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 20 --syn -m state --state NEW -j ACCEPT # ftp-control

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 21 --syn -m state --state NEW -j ACCEPT # ftp-data

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 80 --syn -m state --state NEW -j ACCEPT # http

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 443 --syn -m state --state NEW -j ACCEPT # https

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 465 --syn -m state --state NEW -j ACCEPT # smtp-ssl

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 993 --syn -m state --state NEW -j ACCEPT # imap-ssl

iptables -A FORWARD -p tcp -i $INNER_INT -s $INNER_NET --dport 1443 --syn -m state --state NEW -j ACCEPT # TouchEn key

 

iptables -A FORWARD -p udp -i $INNER_INT -s $INNER_NET --dport 53 -m state --state NEW -j ACCEPT # dns

iptables -A FORWARD -p udp -i $INNER_INT -s $INNER_NET --dport 123 -m state --state NEW -j ACCEPT # ntp

 

iptables -A FORWARD -p icmp --icmp-type echo-reply -j ACCEPT

iptables -A FORWARD -p icmp --icmp-type echo-request -j ACCEPT

 

echo [*] Applying NAT rules...

### NAT ###

## 외부 주소를 내부 주소로 변환해 주기 위한 NAT 설정을 합니다.

## 보통 대부분 외부 주소는 부팅시 마다 IP 주소가 바뀌는 유동 IP로 지정되기 때문에 MASQUERADE 옵션을 사용하는데, 이 옵션은 대신에 CPU의 사용량이 많아 지게 집니다.

## 이렇게 되면 사양이 낮은 임베디드 장비의 경우 CPU 부하로 인해 인터넷 속도가 떨어지는 현상이 발생합니다.

## 따라서 저는 대신에 위에서 외부 IP 주소를 얻어오는 스크립트를 적용하였고 SNAT 옵션으로 외부 IP 주소를 고정적으로 설정하여 CPU 부하를 줄였습니다.

iptables -t nat -A POSTROUTING -s $INNER_NET -o $OUTTER_INT -j SNAT --to-source $IP

 

## 공유기 설정을 위한 IP 포워딩 설정을 해줍니다. 이로써 외부주소를 내부주소로 변환하는 작업이 가능해 집니다.

echo [*] Enabling IP fowarding...

### Enable IP Forwading ###

echo 1 > /proc/sys/net/ipv4/ip_forward

 

echo [*] Setting Up IPTABLES Rules Finished!!!

 

exit 0

 

 

# vi /etc/rc.local

#!/bin/sh -e

#

# rc.local

#

# This script is executed at the end of each multiuser runlevel.

# Make sure that the script will "exit 0" on success or any other

# value on error.

#

# In order to enable or disable this script just change the execution

# bits.

#

# By default this script does nothing.

 

bash /root/bin/iptables.sh

 

exit 0

 

# ifdown eth0

# ifdown eth1

# ifup eth0

# ifup eth1

# bash /root/bin/iptables.sh

[*] Checking if run on the root...

[*] Setting Up IPTABLES Rules...

[*] Applying Variables...

[*] Getting current ip address from Outter Interface...

[*] Flushing current iptables rules...

[*] Changing default policy to DROP...

[*] Applying INPUT rules...

[*] Applying OUTPUT rules...

[*] Loading FTP Passive Connection Tracking Module...

[*] Applying Forward rules...

[*] Applying NAT rules...

[*] Enabling IP fowarding...

[*] Setting Up IPTABLES Rules Finished!!!

 

 

 

[참고] 홈게이트웨어 서버, 홈라우터 서버

기타 기능

Firewall(NAT)

DHCP Server

DNS Server(Caching Only DNS Server)

NTP Client(or NTP Server)

+

보안기능

로드 제어(Load Balancing + QoS(Qaulity of Service))

VPN(EX: OpenVPN)

 

 

 

 

 

 

[참고] 홈게이트웨어 서버, 홈라우터 서버 구축시 기능에 대해서

 

홈게이트웨어 서버, 홈라우터 서버 구축시 기능에 대해서

Firewall(Packet Filtering)

Firewall(NAT)

DHCP Server

DNS Server(Caching Only DNS Server)

NTP Client(or NTP Server)

+

보안기능

로드 제어(Load Balancing + QoS(Qaulity of Service))

VPN(EX: OpenVPN)

 

 

 

 

 

|<--- WAN ----->|                        |<-------- LAN ------------>|

                      (Home Gateway Server)

                        ---------------------      (EX: 192.168.0.0/24)

----------------  eth0           eth1   -----+---------+---------

                        ---------------------         |         |

                  xx.xx.xx.xx        yy.yy.yy.yy     |         |

                                                            Linux     Windows

 

[그림] 네트워크 구성도(예제)

 

 

WAN = eth0 with public IP xx.xx.xx.xx (EX: 5.5.5.5)

LAN = eth1 with private IP yy.yy.yy.yy (EX: 192.168.0.1)

 

 

 

 

 

 

1. NAT 구성 절차(CentOS 5.x 기준)

 

(1) Add 2 Network cards to the Linux box

 

(2) Verify the Network cards, Wether they installed properly or not

# ls /etc/sysconfig/network-scripts/ifcfg-eth* | wc -l

 

(3) Configure eth0 for Internet with a Public ( IP External network or Internet)

# vi /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0

BOOTPROTO=none

BROADCAST=xx.xx.xx.255 # Optional Entry

HWADDR=00:50:BA:88:72:D4 # Optional Entry

IPADDR=xx.xx.xx.xx

NETMASK=255.255.255.0 # Provided by the ISP

NETWORK=xx.xx.xx.0 # Optional

ONBOOT=yes

TYPE=Ethernet

USERCTL=no

IPV6INIT=no

PEERDNS=yes

GATEWAY=xx.xx.xx.1 # Provided by the ISP

-> 통신회사에 따라

() DHCP 서버로 부터 공인 IP를 부여 받는 경우

() 직접 공인 IP를 부여하는 경우

 

(4) Configure eth1 for LAN with a Private IP (Internal private network)

# vi /etc/sysconfig/network-scripts/ifcfg-eth1

BOOTPROTO=none

PEERDNS=yes

HWADDR=00:50:8B:CF:9C:05 # Optional

TYPE=Ethernet

IPV6INIT=no

DEVICE=eth1

NETMASK=255.255.0.0 # Specify based on your requirement

BROADCAST=""

IPADDR=192.168.2.1 # Gateway of the LAN

NETWORK=192.168.0.0 # Optional

USERCTL=no

ONBOOT=yes

 

# service network restart

(5) (Optional) Host Configuration

# vi /etc/hosts

127.0.0.1 nat localhost.localdomain localhost

 

(6) Gateway Configuration

# vi /etc/sysconfig/network

NETWORKING=yes

HOSTNAME=nat

GATEWAY=xx.xx.xx.1 # Internet Gateway, provided by the ISP

 

(7) DNS Configuration

# vi /etc/resolv.conf

nameserver 203.145.184.13 # Primary DNS Server provided by the ISP

nameserver 202.56.250.5 # Secondary DNS Server provided by the ISP

-> 통신 회사의 DNS 서버를 지정한다.

 

(8) NAT configuration with IP Tables

() Delete and flush. Default table is "filter". Others like "nat" must be explicitly stated.

# Flush all the rules in filter and nat tables

# iptables --flush (# iptables -F)

# iptables --table nat --flush (# iptables -t nat -F)

# iptables --delete-chain (# iptables -X)

 

() Delete all chains that are not in default filter and nat table

# iptables --table nat --delete-chain (# iptables -t nat -X)

 

() Set up IP FORWARDing and Masquerading

# iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE

(# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE)

# iptables --append FORWARD --in-interface eth1 -j ACCEPT

(# iptables -A FORWARD -i eth1 -j ACCEPT)

 

() Enables packet forwarding by kernel

# vi /etc/sysctl.conf (# echo 1 > /proc/sys/net/ipv4/ip_forward)

[수정전]

net.ipv4.ip_forward = 0

[수정후]

net.ipv4.ip_forward = 1

 

# sysctl -p

# sysctl -a | grep ip_forward

 

() Apply the configuration

# service iptables save

# service iptables restart

# chkconfig iptables on

 

(9) Testing

() Ping the Gateway of the network from client system

# ping 192.168.2.1

 

() Try it on your client systems

# ping google.com

 

 

[참고] 인터넷상의 문서 참고(NAT 구성)

 

Citrix XenServer

MS Hyper-V

RedHat KVM

VMware Esxi

Oracle OracleVM

 

XenServer 6.2

 

1. for eg. OVH gaves you server with one NIC (eth1) so this is first problem if you aren't using your own server. The answer to this is creating new external network with VLAN (i used 1024) on ETH1 (NIC1) and give this new network an IP in your XenCenter (Networking), for me 10.20.30.1 / 24 - why not :)

 

2. go to console of the serwer and check your interfaces i have (I won't write all):

 

eth1 - external network (OVH - with my static IP) - will call it EXT1

xapi0 - external network for internal use (our 10.20.30.0/24 network) - will call it INT1

xenbr1 - network bridge for vSwitch - all networks

 

 

you can check all information via ifconfig command

 

3. system changes

a. Edit file /etc/sysctl.conf

nano /etc/sysctl.conf

b. Uncomment the following line to enable packet forwarding for IPv4 and other stuff

 

 

net.ipv4.ip_forward = 1net.ipv4.conf.default.proxy_arp = 1net.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0net.ipv4.conf.lo.send_redirects = 0net.ipv4.conf.xenbr0.send_redirects = 0net.ipv4.conf.default.rp_filter = 1net.ipv4.icmp_echo_ignore_broadcasts = 1net.ipv4.conf.default.accept_source_route = 0net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.all.send_redirects = 0kernel.sysrq = 1kernel.core_uses_pid = 1net.ipv4.tcp_syncookies = 1kernel.msgmnb = 65536kernel.msgmax = 65536kernel.shmmax = 4294967295kernel.shmall = 268435456vm.dirty_ratio = 5kernel.printk = 4 4 1 4

 

4. creating NAT

 

$IPTABLES -t nat -A POSTROUTING -s $INT1/255.255.255.0 -j MASQUERADE

$IPTABLES -I RH-Firewall-1-INPUT -s $INT1/24 -j ACCEPT

 

PS. i made a bash script and added it to my starting scripts or you can use add it to /etc/sysconfig/iptables

 

 

5. testing

 

from my VM - ping google.com - OK

 

VM cofig:

IP - 10.20.30.50 (static)

gateway - 10.20.30.1

nameserver - 10.20.30.1

 

I could use command lokkit but in my case there is no MASQUERADE there, that ISP makes it hard as allways !!!

 

 

http://support.citrix.com/article/CTX123930

 

 

 

2. DHCP Server 구성(CentOS 5.X 기준)

 

인터페이스 구성 확인

# cat /etc/sysconfig/network-scripts/ifcfg-eth0

# 3Com Corporation 3c905B 100BaseTX [Cyclone]

DEVICE=eth0

BOOTPROTO=dhcp

HWADDR=00:50:04:84:4B:A4

ONBOOT=yes

 

# cat /etc/sysconfig/network-scripts/ifcfg-eth1

# Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller

DEVICE=eth1

BOOTPROTO=static

HWADDR=00:1C:C0:C3:45:52

IPADDR=192.168.0.1

NETMASK=255.255.255.0

ONBOOT=yes

HOTPLUG=no

 

DHCP 패키지 설치

 

# yum -y install dhcp dhclient

 

/etc/dhcpd.conf 파일 설정

# vi /etc/dhcpd.conf

#

# DHCP Server Configuration file.

# see /usr/share/doc/dhcp*/dhcpd.conf.sample

#

ddns-update-style interim;

ignore client-updates;

 

subnet 192.168.0.0 netmask 255.255.255.0 {

range 192.168.0.2 192.168.0.254;

default-lease-time 43200;

max-lease-time 86400;

option routers 192.168.0.1;

option subnet-mask 255.255.255.0;

option broadcast-address 192.168.0.255;

option domain-name-servers 168.126.63.1;

}

 

(Optional) 아이피 임대 로그 파일(/var/lib/dhcp/dhcpd.leases)

# mkdir -p /var/lib/dhcp

# touch /var/lib/dhcp/dhcpd.leases

 

방화벽 수정(/etc/sysconfig/iptables)

# vi /etc/sysconfig/iptables

# Firewall configuration written by system-config-securitylevel

# Manual customization of this file is not recommended.

*filter

:INPUT ACCEPT [0:0]

:FORWARD ACCEPT [0:0]

:OUTPUT ACCEPT [0:0]

:RH-Firewall-1-INPUT - [0:0]

-A INPUT -j RH-Firewall-1-INPUT

-A FORWARD -j RH-Firewall-1-INPUT

-A RH-Firewall-1-INPUT -i lo -j ACCEPT

-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT

-A RH-Firewall-1-INPUT -p 50 -j ACCEPT

-A RH-Firewall-1-INPUT -p 51 -j ACCEPT

-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT

-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT

-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT

-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

-A RH-Firewall-1-INPUT -m state --state NEW -m udp -p udp --dport 67:68 -i eth1 -j ACCEPT

-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited

COMMIT

 

DHCP 데몬 기동

# service dhcpd restart

 

 

 

3. NTP 설정

 

 

사설망 내부 서버들의 시간 동기화를 위해서, ntp 서버 데몬을 사용하는 방법입니다.

 

먼저 시간의 기준이 되는 서버를 선정합니다. 예로 그 서버가 192.168.100.15 라고 합니다.

그리고, 각 서버들이 192.168.100.x 네트워크에 속해있다고 가정합니다.

 

프로그램 설치

# yum -y install ntp

 

/etc/ntp.conf 파일 수정

사설망내에서 시간의 기준이 되는 예로 192.168.100.15 번 서버는 /etc/ntp.conf 파일에서 다음 부분만 수정하여 설정합니다.

 

# vi /etc/ntp.conf

# Hosts on local network are less restricted.

#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap

restrict 192.168.100.0 mask 255.255.255.0 nomodify notrap # 로컬 서버들이 시간 정보를 가져갈 수 있도록, 접근제한을 풀어줍니다.

 

# Use public servers from the pool.ntp.org project.

# Please consider joining the pool (http://www.pool.ntp.org/join.html).

#server 0.rhel.pool.ntp.org # 기존에 설정된 server 들을 모두 사용하지 않습니다.

#server 1.rhel.pool.ntp.org # 오직 자체 시스템의 클럭만을 시간으로 사용합니다. (이 서버가 기준이므로,)

#server 2.rhel.pool.ntp.org

server <통신회사의 NTP 서버 IP>

 

NTP 데몬 시작

# service ntpd restart

# chkconfig ntpd on

 

방화벽 설정

# vi /etc/sysconfig/iptables

-A RH-Firewall-1-INPUT -m state --state NEW -m udp -p udp --dport 123 -i eth1 -j ACCEPT

 

# service iptables restart

 

테스트

# ntpq -pn

 

 

4. DNS 서버 설정(Caching Only DNS Server)

 

# yum -y install bind bind-utils bind-libs bind-chroot caching-nameserver

# service named restart

# chkconfig named on

 

 

 

상용 방화벽에 대한 그림

 

 

 

 

 

 

6

참고

 

 

 

IPTables 최근 업데이트

http://www.netfilter.org/

 

IPTable 참고 사이트

http://wiki.centos.org/HowTos/Network/IPTables

 

RHEL 4 보안가이드

-http://stuff.mit.edu/afs/athena.mit.edu/project/rhel-doc/4/RH-DOCS/rhel-sg-ko-4/index.html

-https://access.redhat.com/site/documentation/ko-KR/Red_Hat_Enterprise_Linux/5/pdf/Deployment_Guide/Red_Hat_Enterprise_Linux-5-Deployment_Guide-ko-KR.pdf

 

리눅스를 방화벽이 적용된 공유기(Ubuntu/우분투, Debian/데비안 기준)

http://jollaman999.com/10

http://jollaman999.com/11

http://jollaman999.com/12

 

방화벽 설정(CentOS 기준)

http://webdir.tistory.com/170

 

 

Step-By-Step Configuration of NAT with iptables

http://www.howtoforge.com/nat_iptables

http://www.howtoforge.com/internet-connection-sharing-masquerading-on-linux

 

방화벽 시스템에 대한 소개

http://security3-3.tistory.com/2

 

 

 

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160801 TCP Wrapper  (0) 2016.08.01
20160801 NTP  (0) 2016.08.01
20160728 방화벽  (0) 2016.07.28
20160728 로그보안  (0) 2016.07.28
20160727 로그보안  (0) 2016.07.27
Posted by 22Hz
, |


1

iptables 기본 구조

 

iptables넷필터(netfilter) 프로젝트에서 개발했으며 광범위한

프로토콜 상태 추적,

패킷 애플리케이션 계층검사,

속도 제한,

필터링 정책을

명시하기 위한 강력한 매커니즘을 제공한다.

 

 

리눅스 2.4 커널 버전이상에서 사용하는 서버 방화벽(iptables)이다.

리눅스 2.2 커널 버전에서는 ipchains 사용하였는데 구조와 사용하는 방법은 비슷하다.kernel 2.2(ipchains) -> kernel 2.4(iptables) -> kernel 2.6(iptables)# uname -a Linux linux249.example.com 2.6.18-164.el5 #1 SMP Thu Sep 3 03:33:56 EDT 2009 i686 athlon i386 GNU/Linux

(주의) iptables/ipchains 동시에 사용하면 안된다.

 


라우팅 결정패킷의 목적지 주소가 로컬 시스템에 해당되면, 패킷은 로컬 프로세스에 의해 처리되도록 라우팅된다. 패킷이 다른 시스템에 전달될 때 커널에서 패킷 포워딩이 활성화되어 있으면(/proc/sys/net/ipv4/ip_forward), 패킷은 라우팅 테이블 정보에 따라 목적지로 전달된다.

패킷 필터링 지점패킷 필터링은 커널 안의 다섯 개의 필터링 지점에서 발생한다. 필터링 지점 이름은 대소문자를 구별하며 모두 대문자로 이루어진 것에 주의하여야 한다.

 

 

PREROUTING처음 전달 받은 패킷을 처리하는 필터링 지점(nat)

 

FORWARD

로컬 시스템을 통해 경유되는 패킷을 처리하는 필터링 지점(filter)

 

INPUT

라우팅 결정 후에 로컬 시스템으로 향하는 패킷을 처리하는 필터링 지점(filter)

 

OUTPUT

보내기 프로세스를 떠난 패킷을 POSTROUTING 전에 처리하는 필터링 지점(nat/filter)

 

POSTROUTING

시스템을 떠나기 바로 전의 패킷을 처리하는 필터링 지점(nat)

[그림] iptables Packet Filtering Process

 

 

 

 

 

[참고] iptables 관련 용어 정리

테이블(tables)

우선 iptables에는 테이블이라는 광범위한 범주가 있는데 이 테이블은

filter,

nat,

mangle,

raw

같은 4개의 테이블로 구성되며 이중에서 우리에게 필요한 것은 필터링 규칙을 세우는 filter 테이블이다.

 

 

체인(chain)

iptables에는 filter 테이블에 미리 정의된 세가지의 체인이 존재하는데 이는

INPUT,

OUTPUT,

FORWARD

이다. 이 체인들은 어떠한 네트워크 트래픽(IP 패킷)에 대하여 정해진 규칙들을 수행한다.

가령 들어오는 패킷(INPUT)에 대하여 허용(ACCEPT)할 것인지, 거부(REJECT)할 것인지, 버릴(DROP)것인지를 결정한다.

 

INPUT : 호스트 컴퓨터를 향한 모든 패킷

OUTPUT : 호스트 컴퓨터에서 발생하는 모든 패킷

FORWARD: 호스트 컴퓨터가 목적지가 아닌 모든 패킷, 즉 라우터로 사용되는 호스트 컴퓨터를 통과하는 패킷

 

 

 

 

 

 

 

 

 

 

(1) iptables 개요

 

iptables 논리적인 3개의 사슬(chains)으로 구성되어 있고, 각각 INPUT, OUTPUT, FORWARD 라는 이름을 가지고 있다.

또한 관리자가 정의하여 새로운 사슬도 생성할 수 있다. (기본 사슬의 이름은 대문자이다.)

 

 

# iptables -L (# iptables -L -t filter)

Chain INPUT (policy ACCEPT)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

-> 방화벽 설정은 꺼져 있는 상태이다.

 

 

 

(2) iptables 구성

 

INPUT 사슬 : 리눅스 박스를 향해 들어오는 패킷들이 거치는 체인

FORWARD 사슬 : 리눅스 박스를 거쳐 OUTPUT 체인을 향하는 체인

OUTPUT 사슬 : 리눅스 박스를 나가는 패킷들이 들어가는 체인




2

iptables 정책

 

 

(1) iptables 정책 개요

 

방화벽 = 패킷 필터링 + NAT/PAT + (VPN + QoS + ....)

 

패킷 필터링 규칙(Packet Filtering Rule)() 들어 오는 패킷을 순서대로 정의된 규칙(Rule)들을 점검하고 처음 일치되는 규칙을 적용한다.() 하나의 필터링 규칙에 여러가지 조건으로 지정하면 모든 조건에 일치해야 규칙 적용이 된다.() 내장된 체인(Chain) 안을 모두 검사했지만 일치 항목이 없을 경우에는 체인의 기본 정책이 적용된다. "사용자 정의 체인"의 경우 일치 항목이 없을 경우에는 제어권은 "사용자 정의 체인"이 호출되었던 체인으 로 다시 돌아간다.

 

패킷에 대한 동작은 위에서 부터 차례로 각 규칙에 대해 검사하고, 그 규칙과 일치하는 패킷에 대하여 타겟에 지정한 ACCEPT,DROP등을 수행한다.

 

규칙이 일치하고 작업이 수행되면, 그 패킷은 해당 규칙의 결과에 따리 처리하고 체인에서 추가 규칙을 무시한다.

패킷이 체인의 모든 규칙과 매치하지 않아 규칙의 바닥에 도달하면 정해진 기본정책(policy)이 수행된다.

기본 정책은 policy ACCEPT , policy DROP 으로 설정할 수 있다.

 

일반적으로 기본정책은 모든 패킷에 대해 DROP을 설정하고 특별히 지정된 포트와 IP주소등에 대해 ACCEPT를 수행하게 만든다.

 

 

규칙 타겟(Rule Target) : iptables는 패킷이 규칙과 일치할 때 동작을 취하는 타겟을 지원한다.

내장 타겟

ACCEPT : 패킷을 허용하는 옵션이다. (Allow)

DROP : 패킷을 완전히 무시한다. (Deny)

확장 타겟

REJECT : 패킷을 허용하지 않는다는 메세지를 보내면서 거부한다. 사슬 전체 정책 설정(-P)에서는 사용할 수 없. 패킷을 버리고 이와 동시에 적절한 응답 패킷을 전송한다.

LOG : 시스템 로그 커널 장치로 연결한다. 패킷을 syslog에 기록한다.

사용자 정의 체인 : 사용자가 정의하는 체인이다.

 

 

REJECT는 서비스에 접속하려는 사용자의 액세스를 거부하고 connection refused라는 오류 메시지를 보여주는 반면 DROP은 말 그대로 telnet 사용자에게 어떠한 경고 메시지도 보여주지 않은 채 패킷을 드롭한다.

관리자의 재량껏 이러한 규칙을 사용할 수 있지만 사용자가 혼란스러워하며 계속해서 접속을 시도하는 것을 방지하려면 REJECT를 사용하는 것이 좋다.

 

 


 

[그림] 패킷 허용/차단

 



연결 추적(Connection Tracking)

iptables는 연결 추적(connection tracking)이라는 방법을 사용하여 내부 네트워크 상 서비스 연결 상태에 따라서 그 연결을 감시하고 제한할 수 있게 해준다.

연결 추적 방식은 연결 상태를 표에 저장하기 때문에, 다음과 같은 연결 상태에 따라서 시스템 관리자가 연결을 허용하거나 거부할 수 있다

 

NEW 새로운 연결을 요청하는 패킷, , HTTP 요청

ESTABLISHED 기존 연결의 일부인 패킷

RELATED 기존 연결에 속하지만 새로운 연결을 요청하는 패킷, 예를 들면 접속 포트가 20인 수동 FTP 경우 전송 포트는 사용되지 않은 1024 이상의 어느 포트라도 사용 가능하다.

INVALID 연결 추적표에서 어디 연결에도 속하지 않은 패킷

 

상태에 기반(stateful)iptables 연결 추적 기능은 어느 네트워크 프로토콜에서나 사용 가능하다.

UDP와 같이 상태를 저장하지 않는 (stateless) 프로토콜에서도 사용할 수 있다.

 

 

 


 

3

iptables 명령어

 

iptables 설정- 전체 사슬(chains)에 대한 설정(대문자 옵션 사용: -P, -L, -N, -X )- 각 사슬(chains)에 대한 규칙(Rules)을 설정(소문자 옵션 사용: -s, -d, -p )

 

(명령어 형식)

# iptables [-t <table-name>] <command> <chain-name> <parameter-1><option-1> <parameter-n><option-n>

 

 

(1) 전체 사슬에 대한 작동(명령어)

옵 션

설 명

-N

-N, --new-chain chain

Create a new user-defined chain by the given name. There must

be no target of that name already.

 

새로운 사슬을 만든다.# iptables -N NEW # iptables -L

-X

-X, --delete-chain [chain]

Delete the optional user-defined chain specified. There must be

no references to the chain. If there are, you must delete or

replace the referring rules before the chain can be deleted.

The chain must be empty, i.e. not contain any rules. If no

argument is given, it will attempt to delete every non-builtin

chain in the table.

 

비어있는 사슬을 제거한다. 3개의 기본 사슬(INPUT, OUTPUT, FORWARD)은 제거할 수 없다.# iptables -X NEW # iptables -L

-P

-P, --policy chain target

Set the policy for the chain to the given target. See the sec-

tion TARGETS for the legal targets. Only built-in (non-user-

defined) chains can have policies, and neither built-in nor

user-defined chains can be policy targets.

 

사슬의 정책을 설정한다. (EX: ACCEPT, DROP)# iptables -P INPUT DROP ; iptables -L # iptables -P INPUT ACCEPT ; iptables -L

-L

-L, --list [chain]

List all rules in the selected chain. If no chain is selected,

all chains are listed. As every other iptables command, it

applies to the specified table (filter is the default), so NAT

rules get listed by

# iptables -t nat -n -L

Please note that it is often used with the -n option, in order

to avoid long reverse DNS lookups. It is legal to specify the

-Z (zero) option as well, in which case the chain(s) will be

atomically listed and zeroed. The exact output is affected by

the other arguments given. The exact rules are suppressed until

you use

# iptables -L -v

 

현재 사슬의 규칙을 나열한다.# iptables -L # iptables -L -v (# iptables -vL, # service iptables status)# iptables -L INPUT # iptables -L INPUT -v

-F

-F, --flush [chain]

Flush the selected chain (all the chains in the table if none is

given). This is equivalent to deleting all the rules one by

one.

 

사슬으로부터 규칙을 제거한다.# iptables -A INPUT -p icmp -j DROP ; iptables -L# iptables -F ; iptables -L # iptables -A INPUT -p icmp -j DROP ; iptables -L# iptables -F INPUT

-Z

-Z, --zero [chain]

Zero the packet and byte counters in all chains. It is legal to

specify the -L, --list (list) option as well, to see the coun-

ters immediately before they are cleared. (See above.)

사슬내의 모든 규칙들의 패킷과 바이트의 카운트를 '0'으로 만든다.# iptables -Z

[참고] 명령어 정리

-A (--append) : 새로운 규칙을 추가한다.

-D (--delete) : 규칙을 삭제한다.

-C (--check) : 패킷을 테스트한다.

-R (--replace) : 새로운 규칙으로 교체한다.

-I (--insert) : 새로운 규칙을 삽입한다.

-L (--list) : 규칙을 출력한다.

-F (--flush) : chain으로부터 규칙을 모두 삭제한다.

-Z (--zero) : 모든 chain의 패킷과 바이트 카운터 값을 0으로 만든다.

-N (--new) : 새로운 chain을 만든다.

-X (--delete-chain) : chain을 삭제한다.

-P (--policy) : 기본정책을 변경한다.

 

(2) 사슬(chain) 내부의 규칙(Rules)에 대한 작동

 

옵 션

설 명

-A

-A, --append chain rule-specification

Append one or more rules to the end of the selected chain. When

the source and/or destination names resolve to more than one

address, a rule will be added for each possible address combina-

tion.

 

사슬에 새로운 규칙을 추가한다. 해당 사슬에 맨 마지막 규칙으로 등록된다.

-I

-I, --insert chain [rulenum] rule-specification

Insert one or more rules in the selected chain as the given rule

number. So, if the rule number is 1, the rule or rules are

inserted at the head of the chain. This is also the default if

no rule number is specified.

 

사슬에 규칙을 맨 첫부분에 설정한다.(i 대문자)

-R

-R, --replace chain rulenum rule-specification

Replace a rule in the selected chain. If the source and/or des-

tination names resolve to multiple addresses, the command will

fail. Rules are numbered starting at 1.

 

사슬의 규칙을 교환한다.

-D

-D, --delete chain rule-specification

-D, --delete chain rulenum

Delete one or more rules from the selected chain. There are two

versions of this command: the rule can be specified as a number

in the chain (starting at 1 for the first rule) or a rule to

match.

 

사슬의 규칙을 제거한다.

 

 

 

 

 

(3) 필터링 지정 방법

 

옵션과 관련된 규칙

-s(Source IP), -d(Destination IP)

-j(jump)

-!

-p(Protocol)

-i(In-interface), -o(Out-interface)

-t(Tables)

--sport(Source Port), --dport(Destination Port)

 

 

() -s(발신지), -d(도착지) 사용

옵 션

설 명

-s

-s, --source [!] address[/mask]

Source specification. Address can be either a network name, a

hostname (please note that specifying any name to be resolved

with a remote query such as DNS is a really bad idea), a network

IP address (with /mask), or a plain IP address. The mask can be

either a network mask or a plain number, specifying the number

of 1’s at the left side of the network mask. Thus, a mask of 24

is equivalent to 255.255.255.0. A "!" argument before the

address specification inverts the sense of the address. The flag

--src is an alias for this option.

 

출발지 아이피/네트워크를 지정할 때 사용한다.

(주의) 출발지 주소는 반드시 IP 주소로 지정한다. DNS 이름으로 지정할 수 없다. iptables DNS 전에 시작되기 때문에 DNS 이름을 분석 할 수 없다.

-d

-d, --destination [!] address[/mask]

Destination specification. See the description of the -s

(source) flag for a detailed description of the syntax. The

flag --dst is an alias for this option.

 

목적지 아이피/네트워크를 지정할 때 사용한다.

(주의) 목적지 주소는 반드시 IP 주소로 지정한다. DNS 이름으로 지정할 수 없다. iptables DNS 전에 시작되기 때문에 DNS 이름을 분석 할 수 없다.

 

(1) IP 주소로 표시하는 방법

-s 192.168.0.5

(2) 넷마스크값으로 표시하는 방법

-s 192.168.1.0/24 -> CIDR(Classless Inter-Domain Routing) 마스크 표기법 허용

-s 192.168.10.0/255.255.255.0 -> VLSM(Variable Length Subnet Mask) 마스크 표기법 허용

 

# iptables -A INPUT -s 0/0 -j DROP

모든 IP 주소(0/0)로 부터 들어오는 패킷들을 모두 DROP 한다.

 

 

 

 

 

 

() -j(점프) 사용

 

옵 션

설 명

-j

-j, --jump target

This specifies the target of the rule; i.e., what to do if the

packet matches it. The target can be a user-defined chain

(other than the one this rule is in), one of the special builtin

targets which decide the fate of the packet immediately, or an

extension (see EXTENSIONS below). If this option is omitted in

a rule (and -g is not used), then matching the rule will have no

effect on the packet’s fate, but the counters on the rule will

be incremented.

 

특정한 정책을 설정한다.

 

# iptables -A INPUT -s 192.168.1.20 -j DROP

192.168.1.20로 부터 들어오는 모든 패킷에 대해 거부한다.

 

 

 

() !(not 의미) 사용

 

Not의 의미로 사용한다.

 

# iptables -A INPUT -s ! localhost -d 192.168.0.100 -j ACCEPT

localhost가 아닌 호스트에서 192.168.0.100 호스트로 가는 모든 패킷에 대해 허락한다.

 

 

 

() -p(프로토콜) 사용

 

옵 션

설 명

-p

-p, --protocol [!] protocol

The protocol of the rule or of the packet to check. The speci-

fied protocol can be one of tcp, udp, icmp, or all, or it can be

a numeric value, representing one of these protocols or a dif-

ferent one. A protocol name from /etc/protocols is also

allowed. A "!" argument before the protocol inverts the test.

The number zero is equivalent to all. Protocol all will match

with all protocols and is taken as default when this option is

omitted.

 

프로토콜을 설정할 때 사용한다. 보통 TCP, UDP, ICMP 같은 이름들이 사용된다. 대소문자를 구별하지 않는다. !(not)과도 같이 사용할수 있다.

 

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

TCP 프로토콜에 대한 목적지 포트가 23(TELNET)에 대해서 모든 패킷을 허락한다.

 

 

 

() -i(인바운드 인터페이스) 사용

 

옵 션

설 명

-i

-i, --in-interface [!] name

Name of an interface via which a packet was received (only for

packets entering the INPUT, FORWARD and PREROUTING chains).

When the "!" argument is used before the interface name, the

sense is inverted. If the interface name ends in a "+", then

any interface which begins with this name will match. If this

option is omitted, any interface name will match.

 

패킷이 들어오는 인터페이스를 설정할 때 사용한다. INPUT, OUTPUT 사슬에서 주로 사용한다.

 

 

 

() -o(아웃바운드 인터페이스) 사용

 

옵 션

설 명

-o

-o, --out-interface [!] name

Name of an interface via which a packet is going to be sent (for

packets entering the FORWARD, OUTPUT and POSTROUTING chains).

When the "!" argument is used before the interface name, the

sense is inverted. If the interface name ends in a "+", then

any interface which begins with this name will match. If this

option is omitted, any interface name will match.

 

패킷이 나가는 네트워크 장치를 지정할 때 사용한다. 보통 OUPUT, FORWARD 사슬에서 사용된다.

 

 

 

() -t(테이블) 사용

 

옵 션

설 명

-t

-t, --table table

This option specifies the packet matching table which the com-

mand should operate on. If the kernel is configured with auto-

matic module loading, an attempt will be made to load the appro-

priate module for that table if it is not already there.

 

The tables are as follows:

 

filter:

This is the default table (if no -t option is passed). It

contains the built-in chains INPUT (for packets destined to

local sockets), FORWARD (for packets being routed through

the box), and OUTPUT (for locally-generated packets).

 

nat:

This table is consulted when a packet that creates a new

connection is encountered. It consists of three built-ins:

PREROUTING (for altering packets as soon as they come in),

OUTPUT (for altering locally-generated packets before rout-

ing), and POSTROUTING (for altering packets as they are

about to go out).

 

mangle:

This table is used for specialized packet alteration. Until

kernel 2.4.17 it had two built-in chains: PREROUTING (for

altering incoming packets before routing) and OUTPUT (for

altering locally-generated packets before routing). Since

kernel 2.4.18, three other built-in chains are also sup-

ported: INPUT (for packets coming into the box itself), FOR-

WARD (for altering packets being routed through the box),

and POSTROUTING (for altering packets as they are about to

go out).

 

table을 선택할 때 사용한다. filter, nat, mangle 세가지 중에 선택할 수 있다. 커널에 해당 테이블을 지원하는 코드가 들어 있어야 한다. 모듈 자동적재를 선택하면 그와 관련된 커널 모듈이 적재된다. 기본은 filter이므로 nat 사용하려면 nat라고 지정해야 한다.

 

 

 

(o) --sport, --dport 사용

 

옵 션

설 명

--sport

--source-port,--sport [!] port[:port]

--dport

--destination-port,--dport [!] port[:port]

 

 

[참고] 매칭(match) 규칙에 대한 간단한 정리

iptables에서 패킷을 처리할때 만족해야 하는 조건을 가리킨다.

, 이 조건을 만족시키는 패킷들만 규칙을 적용한다.

 

--source (-s) : 출발지 IP주소나 네트워크와의 매칭

--destination (-d) : 목적지 ip주소나 네트워크와의 매칭

--protocol (-p) : 특정 프로토콜과의 매칭

--in-interface (i) : 입력 인테페이스

--out-interface (-o) : 출력 인터페이스

--state : 연결 상태와의 매칭

--string : 애플리케이션 계층 데이터 바이트 순서와의 매칭

--comment : 커널 메모리 내의 규칙과 연계되는 최대 256바이트 주석

--syn (-y) : SYN 패킷을 허용하지 않는다.

--fragment (-f) : 두 번째 이후의 조각에 대해서 규칙을 명시한다.

--table (-t) : 처리될 테이블

--jump (-j) : 규칙에 맞는 패킷을 어떻게 처리할 것인가를 명시한다.

--match (-m) : 특정 모듈과의 매치

 

 

 


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160801 NTP  (0) 2016.08.01
20160729 방화벽  (0) 2016.07.29
20160728 로그보안  (0) 2016.07.28
20160727 로그보안  (0) 2016.07.27
20160727 리눅스 서버보안  (0) 2016.07.27
Posted by 22Hz
, |

6

로그 파일 관리

 

 

(1) 로그 로테이션(Log Rotation)

 

/var/log 디렉토리안에 있는 많은 로그 파일은 기존의 파일에 첨가되는 형태로 기록되기 때문에 그냥 두게 되면 크기는 계속 커지게 된다. 그럼 관리하기 힘들고, 로그 파일안에서 검색하는 속도도 떨어지게 된다. 이를 방지하기 위해서 로그 파일을 정기적으로 조각으로 나누어야 한다. 이런 작업을 하는 프로그램으로 logrotate 명령어가 있다.

 

logrotate 명령어

/etc/logrotate.conf 파일

 

 

# cat /etc/logrotate.conf

# see "man logrotate" for details

# rotate log files weekly

weekly

특별히 명시하지 않은 로그 파일에 대해서는 일주일(weekly)마다 rotate 한다.

 

# keep 4 weeks worth of backlogs

rotate 4

최대 4번까지 rotate를 허용한다.(EX: logfile, logfile.1, logfile.2, logfile.3, logfile.4)

 

# create new (empty) log files after rotating old ones

create

로그 파일을 rotate 한 후에 비어 있는 로그 파일을 생성한다.

 

# uncomment this if you want your log files compressed

#compress

로그 파일을 압축하는 옵션이다. 기본값은 활성화 되어 있지 않다. 용량 문제에 지장이 없다면 압축하지 않을 것을 권장한다.

 

# RPM packages drop log rotation information into this directory

include /etc/logrotate.d

대부분의 RPM 패키지로 설치되는 데몬들은 이 디렉토리에 로그 파일 정책 파일이 생성된다. 각각의 로그 파일을 rotate 시킬수 있도록 하는 설정이다.

# no packages own wtmp -- we'll rotate them here

/var/log/wtmp {

monthly

minsize 1M

create 0664 root utmp

rotate 1

}

로그 파일(wtmp)은 어떤 패키지에 의해서도 설정되지 않기 때문에 따로 설정한다. 다른 로그 파일들은 /etc/logrotate.d 내의 파일들에 모두 각각 설정하고 있다. 한달마다 rotate 하며, 최대 1회까지만 rotate 한다. 관련 파일인 /var/log/utmp 파일을 664 퍼미션을 가지고 소유자는 root로 생성한다.

 

# system-specific logs may be also be configured here.

시스템에서 특별하게 지정하고 싶은 로그 파일들이 있다면 여기에 정의한다.

/var/log/lastlog {

monthly

rotate 3

}

한달마다 rotate 하며 최대 3회가지 rotate 한다.

 

 

# cd /etc/logrotate.d

# ls

acpid cups mgetty ppp rpm sa-update squid tux wpa_supplicant

conman httpd named psacct samba setroubleshoot syslog vsftpd.log yum

 

# cat syslog

/var/log/messages /var/log/secure /var/log/maillog /var/log/spooler /var/log/boot.log /var/log/cron {

sharedscripts

postrotate

/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true

/bin/kill -HUP `cat /var/run/rsyslogd.pid 2> /dev/null` 2> /dev/null || true

endscript

}

 

# ls -l /var/log/messages*

-rw------- 1 root root 240K Mar 23 05:55 /var/log/messages

-rw------- 1 root root 485K Mar 21 01:22 /var/log/messages.1

-rw------- 1 root root 489K Mar 13 21:57 /var/log/messages.2

-rw------- 1 root root 663K Mar 7 13:15 /var/log/messages.3

-rw------- 1 root root 407K Feb 28 03:03 /var/log/messages.4

 

# ls -l /var/log/secure*

-rw------- 1 root root 2.9K Mar 23 03:48 /var/log/secure

-rw------- 1 root root 6.2K Mar 21 00:19 /var/log/secure.1

-rw------- 1 root root 12K Mar 13 21:56 /var/log/secure.2

-rw------- 1 root root 12K Mar 7 13:03 /var/log/secure.3

-rw------- 1 root root 4.9K Feb 28 02:59 /var/log/secure.4

 

# ls -l /var/log/boot.log*

-rw------- 1 root root 0 Mar 21 01:22 /var/log/boot.log

-rw------- 1 root root 0 Mar 14 04:02 /var/log/boot.log.1

-rw------- 1 root root 0 Mar 7 14:08 /var/log/boot.log.2

-rw------- 1 root root 0 Feb 28 04:02 /var/log/boot.log.3

-rw------- 1 root root 0 Feb 24 00:38 /var/log/boot.log.4

 

 

(2) 오래된 로그 삭제

 

로그 파일 이름이 고정되어 있는 경우: /var/log/messages, /var/log/server.log

로그 파일 이름이 고정되어 있지 않은 경우: /var/log/server_1020.log

 

실무에서 많이 사용되는 로그 파일 포맷: server_1020.log (1020일 로그 파일)

 

--------------------------------------------

[참고] find 명령어 형식

# find / -name core type f

# find / -user user01 group user01

# find / -mtime [-7|7|+7]

# find / -size [-10M|10M|+10M]

# find / -perm [-755|755]

# find / -name core -type f -exec rm {} \;

--------------------------------------------

 

# find /Log_Dir -name "*.log" -type f -mtime +30 -exec rm -f {} \;

-> 정상적으로 동작하는 명령어

 

/Log_dir -------- server_0101.log

server_0102.log

server_0103.log

server_0104.log

......

 

# crontab e

0 3 1 * * find /Log_Dir1 -name "*.log" -type f -mtime +30 -exec rm -f {} \;

10 3 1 * * find /Log_Dir2 -name "*.log" -type f -mtime +60 -exec rm -f {} \;

20 3 1 * * find /Log_Dir3 -name "*.log" -type f -mtime +90 -exec rm -f {} \;

-> 매월 13시 정각(새벽시간)/Log_Dir 안의 로그 파일들을 최근 30일 로그만 남기고 모두 삭제한다.

 

 

[EX] 오래된 로그 삭제 실습

# mkdir /waslog

# cd /waslog

# rdate -s 172.16.9.252 (# rdate -s time.bora.net)

 

----------------------------------------------

# date

Sat Jan 10 13:27:03 KST 2015

# date +'%m %d %H:%M:%S'

 

# date +%m%d

# date -d '+45 day' +%m%d

# date -d '1 day ago' +%m%d

# date -d '2 day ago' +%m%d

# date -d '3 day ago' +%m%d

 

# for i in `seq 0 4`

do

touch -t `date -d "$i day ago" +%m%d`1300 file_`date -d "$i day ago" +%m%d`.log

sleep 1

done

------------------------------------------------

# touch file_0116.log file_0115.log file_0114.log file_0113.log file_0112.log

#

 

# ls -l file*

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0112.log

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0113.log

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0114.log

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0115.log

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0116.log

 

# date

-> 01161342

 

# touch -t 01151342 file_0115.log

# touch -t 01141342 file_0114.log

# touch -t 01131342 file_0113.log

# touch -t 01121342 file_0112.log

# ls -l

-rw-r--r-- 1 root root 0 Jan 12 13:42 file_0112.log

-rw-r--r-- 1 root root 0 Jan 13 13:42 file_0113.log

-rw-r--r-- 1 root root 0 Jan 14 13:42 file_0114.log

-rw-r--r-- 1 root root 0 Jan 15 13:42 file_0115.log

-rw-r--r-- 1 root root 0 Jan 16 13:42 file_0116.log

 

Currunt 1 day ago 2 day ago 3 day ago 4 day ago

| | | | |

V V V V V

0116 0115 0114 0113 0112

 

# find /waslog -name "*.log" -type f -mtime +3

-> file_0112.log

 

# find /waslog -name "*.log" -type f -mtime 3

-> file_0113.log

 

# find /waslog -name "*.log" -type f -mtime -3

-> file_0114.log, file_0115.log, file_0116.log

 

# find /waslog -name "*.log" -type f -mtime +3 -exec rm -f {} \;

# find /waslog -name "*.log" -type f mtime +3

 

 

 

 

 

 

 

[실습] 정보 수집

 

(주의) 운영체제 스냅샷

VMware > Snapshot > Take snapshot > 2015_0116

 

(고객) 오늘 중요한 파일(/etc/passwd)이 지워졌다고 보고가 들어 왔다.

(결론) 파일을 지운 사용자에 대한 정보를 수집한다.(최대한 많은 정보를 수집한다.)

 

 

----------------------------------------------------

# rdate -s 172.16.9.252

 

윈도우즈 putty를 통해 서버(172.16.10.2XX)에 접속(user01 사용자)

 

$ su - root

root 사용자로 전환

 

# crontab -l

# tar cvzf /backup/backup_`date +%m%d`.tar.gz /home

# cat /etc/passwd

# cp /etc/passwd /etc/passwd.old

# rm -f /etc/passwd

# exit

$ exit

----------------------------------------------------

 

----------------------------------------------------

 

< CTRL + ALT + <- >

 

오늘 중요한 파일(/etc/passwd)이 삭제 되었다.

() 오늘 파일이 지워졌다.

() 중요한 파일(/etc/passwd)이 지워졌다.

 

사용자의 서버 활동 사항을 추적하여 보고서로 만든다.(1시간)

-> 시간에 기반한 보고서가 만들어져야 한다.(MAC 분석 작업)

 

 

 

 

------------------------- [참고 1]-----------------------------------------

# rdate -s 172.16.9.252

(172.16.9.252)

# chkconfig time-dgram on

# chkconfig time-stream on

# service xinetd restart

 

윈도우즈 putty를 통해 서버(172.16.10.2XX)에 접속(user01 사용자)

# last (# last -f /var/log/wtmp)

# last -f /var/log/wtmp.1

 

# lastlog (/var/log/lastlog)

# lastb (/var/log/wtmp)

 

# who (/var/run/utmp)

 

$ su - root

root 사용자로 전환

# cat /var/log/secure

 

# crontab -l

# cat /var/log/cron

 

# tar cvzf /backup/backup_`date +%m%d`.tar.gz /home

# cat /var/log/backup.log

# cat /etc/passwd

# cp /etc/passwd /etc/passwd.old

# ls /etc/*passwd*

# rm -f /etc/passwd

# cat ~hacker/.bash_history

# cat /home/*/.bash_history | egrep '/etc/passwd'

cat /etc/passwd

rm -f /etc/passwd

# find /home -name .bash_history -exec egrep -l 'rm -f /etc/passwd' {} \;

/home/user01/.bash_history

# exit

$ exit

------------------------------------------------------------------------------------------

---------------------------------- [참고 2] -----------------------------------------------

# pinfo date

-> Examples of date 선택

-> 예제들 중 아래 명령어 예제를 찾는다.

 

# date -d '1970-01-01 UTC 1441155935 seconds' +"%Y-%m-%d %T %z"

-> 시간 출력 포맷을 변경하여 출력

 

# cat ~/.bash_history

#1441086536 2015.03.20 13:00:00 history

history

#1441086605

vi /etc/skel/.bash_logout

#1441088279

clear

#1441088283

unalias ls

#1441088291

useradd hacker

--------------------------------------------------------------------------------------------

 



[과제] 로그파일의 내용 중 자신의 로그인한 기록을 지우는 방법

 

/var/log/wtmp (data file) -> last CMD

/var/run/utmp (data file) -> who CMD

 

# cd /var/log

# mv wtmp wtmp.old

# last

 

# mv wtmp.old wtmp

# last

 

 

 

 

(Hacker) Text Log Format

# cd /var/log

# ls -l secure > secure.time

# vi secure

.... 적당한 라인 삭제 ....

# cat secure.time

# touch -t <시간> secure

 

 

(Hacker) Data Log Format

 

structure

 

# man utmp

# man wtmp

 

 





리눅스침해사고분석보고서_윤진식.hwp

 

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160729 방화벽  (0) 2016.07.29
20160728 방화벽  (0) 2016.07.28
20160727 로그보안  (0) 2016.07.27
20160727 리눅스 서버보안  (0) 2016.07.27
20160726 리눅스 서버보안  (0) 2016.07.26
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함