설치하고 나서 할 일

설정하기에 앞서

CentOS에서 어떠한 작업을 하게된다면 다음의 내용은 반드시 알고 있어야 한다.

설정파일 텍스트(text)파일로 저장되어 있기 때문에 파일을 복사, 수정, 저장 등을 할 수 있어야 한다. 따라서 다음 명령어들의 기본사용법을 알아두어야 한다.

vi - Unix 및 Linux에 쓰이는 표준 편집기

http://www.cals.wisc.edu/calslab/pdf/Vi.pdf

명령 모드와 삽입 모드

대부분의 워드 프로세싱 소프트웨어와는 달리, vi 편집기는 두 가지 모드를 사용합니다

당신은 명령 모드에서 입력 명령

파일에 텍스트를 추가하려면, 삽입 모드에서 이동 i를 눌러, vi 명령을 사용합니다.

당신은 삽입 모드에서 입력 무엇 :

명령 모드로 돌아가려면 Esc 키를 누릅니다.

시스템 업데이트

네트워크가 설정되고 인터넷에 연결되고 나서, 가장 먼저 할 일은 바로 업데이트 작업이다. 최초 배포판이후에 알려진 보안, 버그 업데이트들을 시스템에 적용하는 것이다. 이 작업을 하기 전에 몇가지 참고할 사항을 설명한다.

느린 YUM Public mirror를 제외(exclude) 하는 방법

CentOS의 업데이트 서버 한국 미러서버에 mirror.khlug.org, data.nicehosting.co.kr가 있는데, 속도 제한(QoS)가 설정되어 있는지 1kb/sec의 속도가 나올정도로 상당히 느리다. 이로 인해 업데이트 작업이 엄청나게 오래 걸리게 되므로, 위 서버들은 예외되도록 설정하자.

[root@test1 ~]# cat /etc/yum/pluginconf.d/fastestmirror.conf
[main]
enabled=1
verbose=0
always_print_best_host = true
socket_timeout=3
#  Relative paths are relative to the cachedir (and so works for users as well
# as root).
hostfilepath=timedhosts.txt
maxhostfileage=10
maxthreads=15
exclude=mirror.khlug.org, data.nicehosting.co.kr

이 팁은 커피닉스 IRC채널에서 티니님이 알려주셔서 알게되었다.

보안 관련 설정 중단

정보보호가 강조되는 시대에, 관련 기능을 중단시킨다는 것은 참으로 위험한 일이다. 그러나 본 책의 목적이 일단 LAMP서버 설정에 있으므로, SELinux나 iptables같은 보안 관련 기능은 추후에 다루기로 한다. 일단 LAMP서버 구성에 불편함이 없도록 보안관려된 서비스는 중단하기로 한다.

SELinux

상태 확인

[root@gserver1 ~]# sestatus 
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   permissive
Mode from config file:          permissive
Policy version:                 24
Policy from config file:        targeted

SELinux는 설정을 변경하고 재시작해야 적용된다.

[root@test1 ~]# 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=disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

재부팅 한 후에 확인한다.

[root@gserver1 ~]# sestatus 
SELinux status:                 disabled

iptables(방화벽) 중단

방화벽 기능을 사용하지 않을 경우

chkconfig iptables off
chkconfig ip6tables off

확인

[root@gserver1 ~]# 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

불필요한 서비스 중단

불필요한 서비스를 중단하므로써, 메모리도 절약하고, 보안 취약성도 낮추는등의 장점이 있다. 커널 모듈의 취약점이 발표되는 경우도 종종 있다.

iscsi나 FCoe와 같은 IP기반의 스토리지를 쓰지 않을 경우

chkconfig iscsi off
chkconfig iscsid off
chkconfig fcoe off
chkconfig lldpad off

NFS를 사용하지 않는 경우

chkconfig nfslock off
chkconfig rpcbind off
chkconfig rpcgssd off
chkconfig rpcidmapd off
chkconfig netfs off
[root@gserver1 ~]# chkconfig --list | grep "3:on"
auditd         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
lvm2-monitor   	0:off	1:on	2:on	3:on	4:on	5:on	6:off
network        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
rsyslog        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
sshd           	0:off	1:off	2:on	3:on	4:on	5:on	6:off
udev-post      	0:off	1:on	2:on	3:on	4:on	5:on	6:off

시간서버 설정

서버의 시간을 표준시에 동기화시킨다. 정확한 시간은 서버 장애나 보안사고 발생시, 아주 중요하게 작용하므로 반드시 정확한 시간을 서버에 설정한다.

NTP 설정

[root@gserver1 ~]# yum install ntp
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
 * base: ftp.daum.net
 * extras: ftp.daum.net
 * updates: ftp.daum.net
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package ntp.x86_64 0:4.2.4p8-2.el6.centos will be installed
--> Processing Dependency: ntpdate = 4.2.4p8-2.el6.centos for package: ntp-4.2.4p8-2.el6.centos.x86_64
--> Running transaction check
---> Package ntpdate.x86_64 0:4.2.4p8-2.el6.centos will be installed
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================
 Package                   Arch                     Version                                Repository              Size
====================================================================================
Installing:
 ntp                       x86_64                   4.2.4p8-2.el6.centos                   base                   444 k
Installing for dependencies:
 ntpdate                   x86_64                   4.2.4p8-2.el6.centos                   base                    58 k

Transaction Summary
====================================================================================Install       2 Package(s)

Total download size: 501 k
Installed size: 1.2 M
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 501 k
(1/2): ntp-4.2.4p8-2.el6.centos.x86_64.rpm                                                       | 444 kB     00:00
(2/2): ntpdate-4.2.4p8-2.el6.centos.x86_64.rpm                                                   |  58 kB     00:00
------------------------------------------------------------------------------------Total                                                                                   619 kB/s | 501 kB     00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : ntpdate-4.2.4p8-2.el6.centos.x86_64                                                                  1/2
  Installing : ntp-4.2.4p8-2.el6.centos.x86_64                                                                      2/2

Installed:
  ntp.x86_64 0:4.2.4p8-2.el6.centos

Dependency Installed:
  ntpdate.x86_64 0:4.2.4p8-2.el6.centos

Complete!
[root@gserver1 ~]# cat /etc/ntp.conf
#server 0.centos.pool.ntp.org
#server 1.centos.pool.ntp.org
#server 2.centos.pool.ntp.org
server kr.pool.ntp.org
server ntp.postech.ac.kr
server ntp.xbsd.kr
[root@gserver1 ~]# ntpdate kr.pool.ntp.org
21 Dec 16:58:38 ntpdate[1019]: step time server 222.239.76.224 offset -32.764434 sec
[root@gserver1 ~]# service ntpd start
Starting ntpd:                                             [  OK  ]

[root@gserver1 ~]# chkconfig ntpd on

[root@gserver1 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 118.219.234.251 216.171.124.36   2 u   15   64    1   14.547  -15.373   0.004
 gps-ntp.postech .GPS.            1 u   14   64    1   11.879   -3.321   0.004
 121.182.147.191 .GPS.            1 u   13   64    1   10.341   -3.890   0.004

5-10분 정도 후에 아래와 같이 *, +가 보이면 NTP서버와 시간이 동기화 되는 것이다.

[root@gserver1 ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 118.219.234.251 216.171.124.36   2 u   18   64   17   10.310  -34.335  14.195
*ntp-server.post .GPS.            1 u   17   64   17   12.002  -25.004  15.716
+121.182.147.191 .GPS.            1 u   14   64   17   14.105  -26.837  17.016

SSH보안 및 sudo설정

많은 방법이 있겠지만 최소한 다음 정도는 해주면 될것이다.

참고자료 :

http://fedorasolved.org/post-install-solutions/securing-ssh

편집기로 /etc/ssh/sshd_config 를 열어서 다음과 각 항목들을 변경한다.

[root@gserver1 ~]# cat /etc/ssh/sshd_config 
... 중략 ...
Port 220
... 중략 ...
IgnoreRhosts yes
... 중략 ...
PermitRootLogin no
... 중략 ...
AllowGroups wheel
... 생략 ...

설정을 변경하였으면 sshd를 재시작하여 시스템에 적용한다.

[root@gserver1 ~]# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]

또는

[root@gserver1 ~]# /etc/init.d/sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]

위와 같이 설정하면 일반계정으로 접속후 su - 를 하여 root로 권한을 변경해야하는 번거로움이 생기는데, 이에 대한 편의성을 높여주는 sudo를 설정하여 특정 계정 사용자가 root권한을 편하게 사용할 수 있게 한다.

Connecting to 192.168.0.81:220...
Connection established.
Escape character is '^@]'.

Last login: Wed Dec 21 18:01:30 2011 from 192.168.0.102
[jjun@gserver1 ~]$ su -
Password: 
[root@gserver1 ~]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[root@gserver1 ~]# logout
[jjun@gserver1 ~]$ sudo id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)

sudo 설정

[root@gserver1 ~]# cat /etc/sudoers

중략...

## Same thing without a password
#%wheel	ALL=(ALL)	NOPASSWD: ALL
중략...
[root@gserver1 ~]# cat /etc/sudoers

중략...
## Same thing without a password
%wheel	ALL=(ALL)	NOPASSWD: ALL
중략...

사용자 추가

[root@gserver1 ~]# useradd -G wheel jjun1
[root@gserver1 ~]# passwd jjun1
Changing password for user jjun1.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

테스트

[root@gserver1 ~]# su - jjun1
[jjun1@gserver1 ~]$ sudo id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)
[jjun1@gserver1 ~]$ cat /etc/group | grep wheel
wheel:x:10:root,jjun,jjun1

IPv6 중단

어떠한 이유로 IPv6를 중단할려면 아래와 같이 하면된다. 그러나 CentOS 6 FAQ에 의하면 SELinux등과의 호환성 문제로 권장하지 않는다고 한다.

http://wiki.centos.org/FAQ/CentOS6#head-d47139912868bcb9d754441ecb6a8a10d41781df

참고자료 : http://www.proxar.co.uk/technical-support/technical-forum/how-to-disable-ipv6-on-red-hat-6

[root@gserver1 sysconfig]# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:AC:C1:09  
          inet addr:192.168.0.81  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:feac:c109/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:11605 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1216 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:804736 (785.8 KiB)  TX bytes:138162 (134.9 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:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
[root@gserver1 ~]# echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
[root@gserver1 ~]# reboot
Broadcast message from jjun@gserver1
	(/dev/pts/0) at 14:17 ...

The system is going down for reboot NOW!
[root@gserver1 sysconfig]# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:AC:C1:09  
          inet addr:192.168.0.81  Bcast:192.168.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:759 errors:0 dropped:0 overruns:0 frame:0
          TX packets:87 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:52713 (51.4 KiB)  TX bytes:10010 (9.7 KiB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

프로그램 설치

CentOS에서 무언가를 하고하 한다면, 다음과 같은 절차를 거치게 된다.

  1. 프로그램 설치

  2. 설정

  3. 서비스 시작

  4. 부팅시 시작되게 설정

그 과정에 대한 복잡한 설명은 이 문서와는 어울리지 않는다. 가볍게 건너뛰고 실제 사용법을 따라가 보자.

프로그램 검색

yum list 프로그램이름

프로그램 설치

yum install 프로그램이름

설정

이 단계를 위해서 간단히 vi나 nano같은 편집기 사용방법을 간단하게 알 필요가 있다.

vi 설정파일
또는
nano 설정파일

서비스 시작

service 서비스이름 start
또는
/etc/init.d/서비스이름 start

부팅시 시작되게 설정

chkconfig 서비스이름 on
확인은 
chkconfig --list | grep 서비스이름

반드시 reboot하여 제대로 동작하는지 확인한다.

reboot

패키지 저장소 추가

http://repoforge.org/use/ 에서 RPM 파일을 다운로드 받아서 설치한다.

rpm -Uvh http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

http://fedoraproject.org/wiki/EPEL 에서 RPM 파일을 다운로드 받아서 설치한다.

rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm

http://rpms.famillecollet.com/ 에서 RPM 파일을 다운로드 받아서 설치한다.

rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm

일단은 disabled되게 설정해 놓자.

그리고

http://wiki.centos.org/PackageManagement/Yum/Priorities 를 설정한다.

이 설정은 여러 Repo에 동일한 패키지를 제공할 경우 우선순위를 설정할 수 있게 한다.

사용방법

yum --enablerepo=저장소이름 옵션

[root@gserver1 ~]# yum check-update
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
 * base: centos.mirror.cdnetworks.com
 * epel: mirror.bjtu.edu.cn
 * extras: centos.mirror.cdnetworks.com
 * rpmforge: ftp-stud.fht-esslingen.de
 * updates: ftp.daum.net
[root@gserver1 ~]# yum --enablerepo=remi check-update
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
 * base: mirror.yongbok.net
 * epel: mirror.bjtu.edu.cn
 * extras: mirror.yongbok.net
 * remi: remi-mirror.dedipower.com
 * rpmforge: ftp-stud.fht-esslingen.de
 * updates: mirror.yongbok.net
[root@gserver1 ~]# yum --disablerepo=epel,rpmforge,remi check-update
Loaded plugins: fastestmirror, presto
Loading mirror speeds from cached hostfile
 * base: mirror.yongbok.net
 * extras: mirror.yongbok.net
 * updates: mirror.yongbok.net

DenyHosts 설치

참고자료 :

http://www.ravisaive.in/2011/09/how-to-install-denyhosts-to-block-ssh.html

현재 떠 있는 외부 서비스를 확인해보자.

[root@gserver1 ~]# netstat -antlp | grep LISTEN
tcp        0      0 0.0.0.0:220                 0.0.0.0:*                   LISTEN      951/sshd

sshd 가 있을 것이다. 이 순간에 인터넷이 연결되어 있다면, 이 ssh 서비스를 대상으로 무수한 해킹 및 스캔 시도가 있을 것이다. 이것을 감시하고 차단하는 설정을 하도록 한다.

[root@gserver1 ~]# cat /etc/denyhosts.conf | egrep -v "^#|^$"
       ############ THESE SETTINGS ARE REQUIRED ############
SECURE_LOG = /var/log/secure
HOSTS_DENY = /etc/hosts.deny
PURGE_DENY = 4w
BLOCK_SERVICE  = sshd
DENY_THRESHOLD_INVALID = 5
DENY_THRESHOLD_VALID = 10
DENY_THRESHOLD_ROOT = 1
DENY_THRESHOLD_RESTRICTED = 1
WORK_DIR = /var/lib/denyhosts
SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES
HOSTNAME_LOOKUP=YES
LOCK_FILE = /var/lock/subsys/denyhosts
       ############ THESE SETTINGS ARE OPTIONAL ############
ADMIN_EMAIL = root
SMTP_HOST = localhost
SMTP_PORT = 25
SMTP_FROM = DenyHosts <nobody@localhost>
SMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]
AGE_RESET_VALID=5d
AGE_RESET_ROOT=25d
AGE_RESET_RESTRICTED=25d
AGE_RESET_INVALID=10d
   ######### THESE SETTINGS ARE SPECIFIC TO DAEMON MODE  ##########
DAEMON_LOG = /var/log/denyhosts
 
DAEMON_SLEEP = 30s
DAEMON_PURGE = 1h
   #########   THESE SETTINGS ARE SPECIFIC TO     ##########
   #########       DAEMON SYNCHRONIZATION         ##########

/etc/hosts.allow

sshd: 192.168.0.33, 192.168.0.44

/etc/hosts.allow 파일이 /etc/hosts.deny 보다 우선한다. 즉, /etc/hosts.deny에 IP가 등록되어 있어도 /etc/hosts.allow에 IP가 있다면, 차단하지 않는다.
[root@gserver1 denyhosts]# ll
total 36
-rw-r--r--. 1 root root  39 Dec 22 17:51 allowed-hosts
-rw-r--r--. 1 root root  27 Dec 22 17:19 allowed-warned-hosts
-rw-r--r--. 1 root root  81 Dec 22 17:56 hosts
-rw-r--r--. 1 root root  81 Dec 22 17:56 hosts-restricted
-rw-r--r--. 1 root root  81 Dec 22 17:56 hosts-root
-rw-r--r--. 1 root root  81 Dec 22 17:56 hosts-valid
-rw-r--r--. 1 root root  80 Dec 22 17:56 offset
-rw-r--r--. 1 root root   0 Dec 22 17:56 suspicious-logins
-rw-r--r--. 1 root root 190 Dec 22 17:56 users-hosts
-rw-r--r--. 1 root root   0 Dec 22 17:56 users-invalid
-rw-r--r--. 1 root root  64 Dec 22 17:56 users-valid
[root@gserver1 denyhosts]# grep 192.168.0.102 *
allowed-warned-hosts:192.168.0.102
hosts:192.168.0.102:0:Thu Dec 22 17:14:45 2011
hosts-restricted:192.168.0.102:0:Thu Dec 22 17:14:45 2011
hosts-root:192.168.0.102:2:Thu Dec 22 17:14:45 2011
hosts-valid:192.168.0.102:1:Thu Dec 22 17:52:00 2011
users-hosts:jjun - 192.168.0.102:1:Thu Dec 22 17:52:00 2011
users-hosts:root - 192.168.0.102:2:Thu Dec 22 17:14:45 2011
[root@gserver1 denyhosts]# tail -f /var/log/secure 
Dec 22 17:51:50 gserver1 sshd[1578]: Failed password for jjun from 192.168.0.102 port 49859 ssh2
Dec 22 17:51:52 gserver1 sshd[1578]: Accepted password for jjun from 192.168.0.102 port 49859 ssh2
Dec 22 17:51:52 gserver1 sshd[1578]: pam_unix(sshd:session): session opened for user jjun by (uid=0)
Dec 22 17:51:56 gserver1 sshd[1578]: pam_unix(sshd:session): session closed for user jjun
Dec 22 17:53:22 gserver1 sshd[1612]: Accepted password for jjun from 192.168.0.33 port 1701 ssh2
Dec 22 17:53:22 gserver1 sshd[1612]: pam_unix(sshd:session): session opened for user jjun by (uid=0)
Dec 22 17:54:44 gserver1 sshd[1639]: refused connect from 192.168.0.102 (192.168.0.102)
Dec 22 17:55:33 gserver1 sshd[1645]: Accepted password for jjun from 192.168.0.102 port 49865 ssh2
Dec 22 17:55:33 gserver1 sshd[1645]: pam_unix(sshd:session): session opened for user jjun by (uid=0)
Dec 22 17:55:34 gserver1 sshd[1645]: pam_unix(sshd:session): session closed for user jjun

# jjun이 로그 아웃함
Dec 22 17:58:07 gserver1 sshd[1620]: channel_by_id: 0: bad id: channel free
Dec 22 17:58:07 gserver1 sshd[1620]: Disconnecting: Received ieof for nonexistent channel 0.
Dec 22 17:58:07 gserver1 sshd[1612]: pam_unix(sshd:session): session closed for user jjun

자 이제 LAMP 설치를 위한 기본 OS 준비가 끝났다. 기존의 서적들이 대부분 소스 컴파일 형태로 설명하였으나, 본 책에서는 RPM 설치를 통해 설명한다.