rdate 명령을 사용하시면 됩니다.

#rdate -s time.kriss.re.kr [한국표준연구소의 Time Server]

부팅시 매번 정확한 시간을 셋팅하려면 /etc/rc.d/rc.local 파일에 한라인 추가해 주시면 됩니다.
혹은 크론(cron)을 이용하여 일정한 간격으로 시간을 갱신해 줄수 있습니다.
2005/06/27 18:27 2005/06/27 18:27
root password를 잊어버려 root로 login이 않되는 경우에는 OS CD를 사용하여 아래와 같이 복구를 할 수 있습니다.. 만약 OS CD를 갖고있지 않다면 복구할 방법이 없습니다.

1. 시스템을 down 시키고 OS CD를 CD-ROM drive에 넣는다.

root로 login을 할수 없으므로 시스템을 재부팅 시키기 위해서는 keyboard에서 "stop" key와 "a" key를 동시에 눌러서 시스템을 PROM mode(ok prompt 상태) 로 전환한다

2. 아래와 같이 CDROM 을 이용하여 single-user mode로 부팅한다

ok boot cdrom -sw

3. Bourne shell prompt(#)가 나타나면, /로 사용하던 disk device를 /a로 mount 한다.
/로 사용하던 disk device가 /dev/dsk/c0t0d0s0인 경우 아래와 같이 한다.

# mount /dev/rdsk/c0t0d0s0 /mnt

4. 위와 같이 하면 기존에 /etc directory에 있던 shadow 화일이 /a/etc/shadow로 존재하게 되며, 이 화일을 vi로 열어서 root에 정의되어 있는 password부분을 지운다.
# TERM=vt100
# export TERM
# vi /a/etc/shadow
root:vBrrOh8AIqYV6:6445::::::
vBrrOh8AIqYV6 <-- 이 부분을 지운다

변경후

# cat /a/etc/shadow
root::6445::::::

5. 위와 같이 한후 시스템을 재부팅 하면 root로 password 없이 login가능 합니다..
2005/06/27 18:26 2005/06/27 18:26
리눅스싱글 모드로 들어 갑니다..

ex) boot : linux single 혹은 linux 1

그런 후 프롬프트 상태에서 passwd를 입력한 후

새로운 패스워드를 입력 하시면 됩니다.
2005/06/27 18:25 2005/06/27 18:25
요즘 up2date 가 잘 되다가 안된다는 문의전화가 많이 오고있습니다.

RHN Errata 를 자주 확인하시는 분들은 벌써 알고 계시겠지만...

8월29일자 인가 up2date의 SSL 인증 관련부분의 패치가 있었습니다.

먼저 패치를 적용시키고 up2date를 실행시키면 다시 잘 됩니다.

소스 RPM을 다운받으셔서 리빌드하신후 rpm을 업데이트 시키세요~

- redhat7.3 : ftp://updates.redhat.com/7.3/en/os/SRPMS/up2date-2.8.40-3.7.3.src.rpm
- redhat8.0 : ftp://updates.redhat.com/8.0/en/os/SRPMS/up2date-3.0.7.2-1.src.rpm
- redha9 : ftp://updates.redhat.com/9/en/os/SRPMS/up2date-3.1.23.2-1.src.rpm

그리고, 처음 up2date를 설치하셔서 하시려는 분은 rhn_register 도 업데이트 하시고,
rhn에 등록을 하셔야 합니다.

- redhat7.3 : ftp://updates.redhat.com/7.3/en/os/SRPMS/rhn_register-2.8.27-1.7.3.src.rpm
- redhat8.0 / redhat9 은 up2date 패키지에서 --register 옵션으로 바로 rhn 등록이 가능하므로
필요없습니다.
2005/06/27 18:25 2005/06/27 18:25
rpm 은 Redhat Package Manager 로 말 그대로 패키지 관리자이다.

패키지 파일을 버전으로 관리하는 rpm은 RedHat에서 개발한 자동 갱신 소프트웨어인

up2date로 언제나 최신버전을 유지할 수 있다.

그러나 up2date 는 https://rhn.redhat.com 에 가입해야만 사용할 수 있는

소프트웨어이다. 물론 60일 무료계정을 이용할 수 있으며,

기한이 만기되면 간단한 설문조사를 하면 다음 60일까지 무난히 쓸 수 있다.

ㅡ0-) 그러나... 설문조사 마져도 귀차니즘 압박에 시달리는 사람과,

RedHat에서 공식 배포하지 않는 패키지(ex. RedHat9에서 ProFTPd를 제공하지 않는다)를 사용하는 사람에게

매우 좋은 autoupdate라는 프로그램이 있다.

autoupdate는 단순히 RedHat 배포판에만 적용되는 것이 아니라

rpm을 사용하는 Mandrake, SUSE 같은 배포판에도 적용할 수 있다.

Officaial Site : http://www.mat.univie.ac.at/~gerald/ftp/autoupdate

autoupdate는 Perl 로 쓰여진 언어이다. rpm, perl, perl-DB_File, perl-RPM2 등의

패키지가 필요하며 모든 것은 위의 홈페이지에서 받을 수 있다.
(perl용 FTP모듈은 최신버전 Perl 패키지에 포함되어 있다. 만약 없으면 위의 홈페이지에서
perl-libnet 패키지를 받자)

위의 사이트에서 autoupdate-xxx.rpm 와 autoupdate-cfg-배포판-xxx.rpm 을 받는다.
(xxx는 버전)

받은 모든 rpm을 설치한다.

$ rpm -Uvh *.rpm (받은 rpm 만 있는 디렉토리에서...)



설치는 다 됐다. 이제 단순히 autodld 라고 치면 up2date 와 비스무레한 행동을 할 것이다.


$ autodld
Found no new rpms at ftp.redhat.com.
Checking selected rpms.
Found no rpms to upgrade.
(흠... 모든 소프트웨어가 최신 버전이로군)


만약 새로 설치하고 싶은 패키지가 있다면 autoget을 이용하자.


$ autoget mod_ssl
New rpms from ftp.redhat.com:
mod_ssl-2.0.40-11.7.i386.rpm
Checking selected rpms.
Installing rpms:
mod_ssl-2.0.40-11.7.i386.rpm
Removing updated rpms:
mod_ssl-2.0.40-11.7.i386.rpm
(apache용 ssl 모듈을 설치해봤다.)


예제엔 나오지 않았지만 autoupdate는 up2date와 같이 의존성을 검사하여

필요한 패키지까지 모두 받아온다.

up2date는 rhnsd 이라는 Daemon을 이용하여 2시간마다 RedHat에 접속하여

새 패키지를 검사한다. (검사하는 속도가 좀 빠르긴 하지만...)

autoupdate 역시 비슷한 역할을 시킬 수 있다. cron을 이용해서 말이다.


(RedHat8 기준)
$ cd /etc/cron.daily
$ ln -s /usr/sbin/autodld


매일 한 번씩 autodld가 자동으로 실행된다.

물론 주기를 다르게 해서 등록하고 싶다면 다른 디렉토리나 /etc/crontab 을

수정을 해주면 되며 이러한 사항은 Cron HOWTO나 cron manpage를 참조하기 바란다.
2005/06/27 18:24 2005/06/27 18:24
시스템 관리자를 위한 50가지 비법

리눅스 시스템 관리자가 되기 위해서는 많은 것을 알아두어야 한다. 시스
템 관리자의 관리 여하에 따라 많은 사람들의 시스템 장애를 초래할 수 있
기 때문이다. 물론 시스템 관리자가 모든 것을 미리 예방할 수는 없다. 하
지만 불가피한 상황을 제외하고는 시스템이 정상적으로 작동되도록 해야한
다.
이번 호에서는 시스템, 네트워크, APM, 메일, 보안, 장애 발생시 복구 등
에서 일어날 수 있는 시스템 관리자의 행동요령에 대해 알아볼 것이다. 시
스템 관리자는 항상 모니터와 키보드와 함께 한다는 사실을 기억해야 한
다.

막강한 시스템 길들이기

시스템이 네트워크에 연결되어 있다면, 다음과 같이 한국 표준시간 서버에
서 표준시간을 받아서 설정할 수 있다.

# rdate -s time.kriss.re.kr

시스템이 온라인 상태가 아니라면 아래와 같이 수동으로 설정할 수도 있
다.

# date -s ?1999-12-30 22:22:40?

위와 같이 실행하면 실행할 때만 적용되므로 이후 시간이 늦어지는 것을
막기 위해서는 주기적으로 변경 가능하게 크론(/etc/crontab)에 설정하는
것이 좋다.
.profile은 로그인시 적용되는 내용들이고, rc.local은 시스템 부팅시 실
행해야 할 것들을 적어 놓은 것이다. 사용자 홈디렉토리의 .profile
이 /etc에 있는 설정 파일보다 우선하기 때문에 홈 디렉토리에 .profile
에 패스를 설정해주거나 쉘 환경 파일 등을 설정해 주면 계정 내에서 적용
이 된다. rc.local에는 부팅시 가장 마지막에 실행되므로 일반적으로 부팅
시 실행되어야 할 데몬 등을 적어준다.

리눅스 시스템의 자원 정보는 proc 파일시스템 구조를 통해서 알 수 있
다. 이는 실제로 디스크 용량을 차지하는 파일들이 아닌 가상의 디렉토리
구조이며 리눅스 커널에 의해 사용되는 시스템의 정보를 담는 곳으로 사용
된다. 다음의 위치에서 하드웨어에 대한 정보 및 시스템 관련 정보들을 확
인할 수 있다.
위와 같이 관련된 정보에 해당하는 파일 이름이 존재한다. 이 파일들은 텍
스트 포맷이므로 cat 명령을 통해서 확인할 수 있다


^M 문자를 공백으로 치환하면 된다.

:1,$s/^M//g

# rpm -qa | grep 패키지 명으로 확인할 수 있다.


rpm2cpio filename.rpm | cpio -I -make-deretories -E filename

Tcp Syn Flooding은 웹으로의 공격이 대부분이므로 syn_recv 프로세스가
일정 개수가 넘게 되면 아파치를 재시작한다. 지속적인 공격일 경우 대처
방안으로 두 가지 방법이 있다.
첫째, sysctl -a |grep syn_backlog으로 확인 후 backlog를 늘려주거나 둘
째, sysctl -a |grep syncookies로 확인 후 syncookies의 값을 1로 바꾸어
준다. syn_backlog의 값을 조정해주는 방법은 다음과 같다.

# sysctl -w net.ipv4.tcp_max_syn_backlog=1024
# echo 1024 > /proc/sys/net/ipv4/tcp_max_syn_backlog

syncookies의 값은 다음과 같이 변경이 가능하다.

# sysctl -w net.ipv4.tcp_syncookies=1

Umount시 위와 같은 메시지가 나는 것은 unmount하려는 디렉토리에서 실행
되고 있는 프로세스가 있기 때문이다. 예로 /tmp 디렉토리를 umount시키
려 할 때 위의 메시지가 뜨는 경우 mysql. socket파일이 /tmp에 있는 경우
를 들 수 있다. 이 경우에는 해당 파일시스템에서 실행중인 프로세스를 제
거해야 하나 일일이 제거가 번거로우므로 Fuser에서 -k 옵션을 사용하면
간단히 해결할 수 있다.

Fuser -km 장치명

디렉토리나 파일 퍼미션 중 setuid는 소유자의 권한을 잠시 빌려 실행 후
권한을 돌려주고 실행을 마치게 되는데 실행도중 인터럽트가 발생한다면
정상적으로 권한을 반환하지 못하게 되어 소유자의 권한을 그대로 가지고
있게 된다. 이때 파일의 소유자가 루트였다면 이것은 보안에 문제가 될
수 있으며 이런 점을 이용해 해킹에 많이 사용된다. Setuid가 걸려 있는
파일 중에 실행권한이 있으며 루트권한일 경우에는 위험하다. 특정 디렉토
리에서 setuid가 걸려있는 파일을 찾으려면 find /usr -perm 4755와 같이
perm 옵션으로 찾을 수 있다.

다음과 같이 ~/.bash_profile를 실행해서 변경이 적용되도록 한다.

# source ~/.bash_profile

리눅스 시스템을 재부팅하고 lilo가 뜨면 ‘linux single’로 부팅한다.
Tab 키를 누르면 등록되어 있는 라벨이 모두 보이므로, 여기에서 선택하도
록 한다. 부팅 후 쉘 명령어 화면에서 /etc/passwd 파일에서 암호 부분을
삭제하거나 passwd를 실행하여 루트의 패스워드를 새로 설정해 준다.

# passwd root

위의 명령을 입력한 후 변경할 패스워드를 입력하면 된다.

보통 파티션을 나누는 것에 대해서 별다른 고려 없이 /로 모든 것을 잡아
서 설치하는 경우가 종종 있다. 이럴 경우 설치시 편리하지만, 나중에 파
일시스템에 문제가 생기거나 효율적으로 파티션을 관리하기에는 많은 어려
움이 있다. 파티션을 나눌때는 어떤 용도로 쓸 것인지에 대해서 충분히 생
각한 후 파티션을 해야 한다. 다음은 9.1GB 스카시 하드디스크를 기준으
로 웹 서버에 이용될 서버에 대해 파티션한 경우의 예다.
/var 디렉토리와 같이 항상 새로운 자료가 쌓이는 곳은 안전성이 우선시
되므로, ext3 파일시스템이 유리하며, /usr와 같이 내용 변화 없이 빠르
게 액세스하여 쓸 수 있어야 하는 부분은 ext2 시스템을 이용하여 성능에
초점을 두면 좋을 것이다.

1024KB인 경우에는 블럭이 작은 만큼 4096KB보다 하드의 낭비가 적다.
1023KB의 데이터를 저장하는 경우, 기본 블럭사이즈가 1024KB일 때는 1K
공간이 사용되지만, 4096KB가 기본 블럭이라면 4K를 차지하게 된다. 하지
만 아주 작은 파일들이 많은 경우 해당 데이터를 액세스하는 데는 1024KB
가 4096KB보다 더 걸리게 되므로 퍼포먼스가 급격히 떨어지게 된다. 따라
서 자신이 이용하는 시스템의 특성과 용도에 맞게 블럭 사이즈를 지정해
서 사용하면 된다.

RAID는 ‘Redundant Array of Inexpensive (or Independant) Disks’의 약
어다. RAID 시스템은 여러 드라이브의 집합을 하나의 저장장치처럼 다룰
수 있게 하고, 장애가 발생했을 때 데이터를 잃어버리지 않게 하며 각각
에 대해 독립적으로 동작할 수 있도록 한다.

시스템의 다운, 데이터 손실에 대비하여 보통 여러 가지 RAID 레벨 중에
서 1과 5번 방법을 많이 사용한다.
RAID 1(mirroring)의 특징은 빠른 기록 속도와 함께 장애 복구 능력이 있
다는 것이다. 2대의 드라이브만으로 구성할 수 있기 때문에 작은 시스템
에 적합하다. 읽을 똑같은 하드가 복제되고 있으므로, 시스템에 문제 발생
시 서비스 지연 시간이 매우 짧아서 웹 서비스를 하는 곳에서 유용하게
쓸 수 있다. 하지만 한 하드의 내용이 또 다른 하드에 똑같이 복사되므로
하드용량의 낭비가 심하다.
RAID 5(distributed parity)는 작고 랜덤한 입출력이 많은 경우 더 나은
성능을 제공한다. 빠른 기록 속도가 필수적이지 않다면, 일반적인 다중사
용자 환경을 위해 가장 좋은 선택이다. 그러나 최소한 3대, 일반적으로는
5대 이상의 드라이브가 필요하다. 변경된 내용이 있을 경우 그것만 기록한
다. 일반적으로 RAID 1은 ECC 계산을 하지 않으므로 RAID 5보다 빠르고,
raid5는 하드 공간을 좀 더 여유있게 쓸 수 있다는 장점을 지닌다.

먼저 시스템의 전체 용량이 어떻게 되고, 그 중에서 백업할 가치가 있는
것은 어떤 부분인지를 결정한다. 사용할 백업 장비와 종류를 알아보고,
총 백업 시간과 어느 정도 부하가 걸리는지 예상해보고 테스트 해 본 후
마지막으로 백업 스케줄을 정한다. Full 백업은 백업할 자료를 처음부터
끝까지 다 기록하는 것이고, Incremental 백업은 이전의 데이터와 비교해
서 새로 추가된 내용만 백업하는 방법이다. 따라서 Full 백업시 완전히 데
이터를 백업할 수 있지만 시간이 많이 걸리고, 시스템에 부하를 초래할
수 있는 반면에 Incremental 백업은 빠른 시간내에 백업을 할 수 있지만,
백업하는 시간에 따라 데이터가 완전히 백업되지 못할 경우도 있을 수 있
다.

SNMP는 ‘Simple Network Management Protocol’의 약자다. 네트워크에 연
결되어 있는 장치에서 네트워크에 관련된 정보를 모으고 문제점 등을 보고
할 수 있는 기능을 제공하는 프로토콜이다. 구성 요소는 에이전트와 매니
저가 있다. 이것은 서버/클라이언트 구조로서 에이전트가 서버에 해당되
고, 매니저가 클라이언트에 해당한다. 에러가 발생하는 경우는 선택한 장
비에 SNMP가 Enable이 안 되었거나, 네트워크에 문제가 있어서 모니터링
하려는 장비까지 프로토콜이 전송되지 않는 경우, community 값이 잘못 사
용된 경우 등이 있다.

/etc/rc.d/init.d이 디렉토리에 있는 서비스를 ‘서비스명’ stop 또는
start 시키거나 재시작시킨다.

quota를 이용하면 된다. df 명령으로 사용자의 홈디렉토리가 있는 디바이
스를 확인한다.

ilesystem 1k-blocks Used Available Use% Mounted on
/dev/sda5 3028080 878480 1995780 31% /
/dev/sda1 62217 7713 51291 13% /boot
/dev/sda6 2759260 2088820 530276 80% /home2
/dev/sdb1 8744304 6496724 1803388 78% /home3
/dev/sdc1 35296928 25597968 7905940 76% /home4
/dev/sda10 202220 6 191774 0% /tmp
/dev/sda7 1517920 1280648 160164 89% /usr
/dev/sda8 608724 426992 150812 74% /var
# edquota username
Quotas for user jhk1:
/dev/sda6: blocks in use: 47584, limits (soft = 0, hard = 0) /* 이 부
분에 설정 */
inodes in use: 4590, limits (soft = 0, hard = 0)
/dev/sda8: blocks in use: 4, limits (soft = 0, hard = 0)
inodes in use: 1, limits (soft = 0, hard = 0)
Soft는 용량에 설정되어 있는 용량은 넘어도 어느 정도 여유가 있지만,
hard 용량에 설정된 크기는 절대적이다. 따라서 hard 용량을 사용자는 넘
을 수 없다. 일반적으로 soft 용량을 hard 용량보다 조금 더 적게 설정해
놓는다. 쿼터 조정후 quotacheck /dev/sda6를 해줘서 체크를 해 주도록 한
다.

파일명이 하이픈(-)으로 시작하는 파일

rm ./-filename 상대경로를 이용하여 파일명을 지정해줌
rm -- -filename --를 이용 그 이후에 오는 '-filename'이라는 파일이 옵
션이 아닌 파일이라는 것을 밝힘

/etc/inittab에서 사용하지 않은 가상콘솔 레벨을 주석처리 해주면 된다.

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
#4:2345:respawn:/sbin/mingetty tty4
#5:2345:respawn:/sbin/mingetty tty5
#6:2345:respawn:/sbin/mingetty tty6


먼저 psacct라는 패키지가 필요하다. 설치되지 않은 경우 rpm이나 소스 등
을 직접 설치 한다(대부분 배포본에 기본적으로 포함되어 있으므로 그대
로 사용하면 된다). 다음과 같이 명령하면 사용한 명령어를 확인할 수 있
다.

더미 로그 파일 생성(데이타를 기록할 파일 생성)
# touch /var/log/pacct
# /sbin/accton /var/log/pacct 체크를 시작하게 하는 명령어 실행
# lastcomm 사용자계정 사용자가 수행한 명령어 체크 */
tar xvfpz 압축파일 또는 .tgz -C 특정경로 특정 파일의 절대경로(또는 파
일명)로 입력하면 된다. test.tgz 파일에서 /home/test /test.txt파일
을 /tmp 디렉토리에 압축해제를 한다면, tar xvfpz test.tgz -
C /tmp /home/test/test.txt와 같이 하면 된다.

TTL이란 Time To Live의 약자다. 이것은 라우팅 에러로 인하여 데이터그램
이 네트워크를 영원히 떠돌아다니는 것을 방지한다. 라우터는 네트워크 간
을 이동하는 데이터그램의 TTL 필드를 감소시키며 TTL 필드가 0이 되는 데
이터그램은 버린다(drop). IPv4 멀티캐스트에서 TTL은 문턱값(threshold)
의 의미를 지닌다.
다음 예를 보면 그 용도가 분명해진다. 회사에서 모든 호스트가 속하는 아
주 길고 대역폭에 한 부서가 대역폭을 많이 차지하는 인터넷 방송을 한다
면, 랜에는 엄청난 용량의 트래픽이 발생할 것이다. 인터넷 방송도 하길
원하지만, 멀티캐스트 트래픽 때문에 인터넷 전체가 마비되어서는 안된
다. 멀티캐스트 트래픽이 라우터간을 얼마나 멀리까지 이동할 수 있도록
할 것인지 제한할 필요가 있다. 이것이 TTL의 용도다.

TCP Wrapper를 사용하는 방법과 ipchains를 사용할 수 있는데 커널 2.4 버
전부터는iptables을 사용한다. hosts.allow와 hosts. deny를 사용한다면,
hosts.deny 파일에서 다음과 같이 모두 제한을 한다.

all : ALL

hosts.allow 파일에서 허용할 IP를 여러 개 설정할 경우 다음과 같이 스페
이스로 구분하여 준다.

all : xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx ....

ipchains나 iptables의 경우에는 다음과 같이 설정하여 주면 된다.

# ipchains ?A input ?s xxx.xxx.xxx.xxx ?j DENY
# iptables ?A INPUT ?s xxx.xxx.xxx.xxx ?j DROP

안전한 네트워크 다지기

시스템에 기본적으로 설치된 아래의 명령들을 사용하여 네트워크가 정상적
으로 작동하지 않는 경우 여러 가지 테스트를 해볼 수 있다.
/etc/sysconfig 디렉토리 밑에 하드웨어에 대한 정보가 나오는데 이더넷
카드가 여러 개 꽂혀 있다면 ifcfg-eth1, ifcfg-eth2 식으로 확인할 수 있
다.

/etc/sysconfig/network-scripts/ifcfg-eth0

#cat ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static /* 정적 아이피 */
BROADCAST=211.47.64.255
IPADDR=211.47.64.80
NETMASK=255.255.255.0
NETWORK=211.47.64.0
ONBOOT=yes /* 부팅시 자동인식 */

사용하는 IP를 변경하거나, 새로운 네트워크 카드 추가시에는 ifcfg-eth0
파일을 수정한 후에 반드시 ifdown ifcfg-eth0, ifup ifcfg-eth0 명령을
실행해 주어야 변경된 IP가 적용된다. 또는 /etc/rc.d /init.d/network
restart를 실행해 주어도 된다.

Apache + PHP + MySQL

아파치에만 적용되는 내용은 아니지만 standalone으로 설정할 경우에
는 /etc/rc.d/rc.local나 /etc/rc.d/rc3.d/밑에 설정되어 데몬으로 실행되
며, inetd로 설정할 경우 /etc/inetd.conf에 추가되어 실행되어 텔넷이나
FTP와 같이 시스템 프로세스로 실행되므로 접속이 많은 httpd 인 경우
standalone으로 설정하여야 한다. 그리고 inetd로 설정시에는 한정된 프로
세스만 수용 가능하며 반응속도가 standalone 방식에 비해 느리다.

httpd -t 옵션으로 우선 syntax error부터 확인한 후 syntax error가 있
으면 먼저 수정을 해주고 Logs 디렉토리에서 에러 로그 파일을 확인하여
수정 후 재실행한다.

php3 버전의 경우 index.php3을 php4의 경우 index.php라는 파일을 다음
과 같은 내용으로 작성하여 웹에서 열어보면 버전 및 연동 현황을 확인할
수 있다.

phpinfo();
?>

먼저 php설치 후 apache 컴파일시 php 모듈 넣어서 재컴파일 해준다.
./configure --prefix=/usr/local/apache --activate-
module=src/modules/php4/libphp4.a

아파치에서 bandwidth 모듈이 삽입되어 있는 상태라면 모든 호스트에 대
해 1024byte로 속도를 제한하기 위해 아파치에서 설정해 주는 부분은 다음
과 같다. Httpd.conf에서 BandWidthModule On라고 설정 후 BandWidth all
1024라고 설정한다.

아파치에서 index.html 파일이 없을 때 디렉토리 목록 출력을 원하지 않
을 경우에는 DocumentRoot 디렉토리쪽에 설정되어져 있는 옵션에서
Indexes를 삭제한다. 또한 특정 디렉토리에서만 인덱스를 허용치 않을 경
우에는 특정 디렉토리의 .htaccess 파일안에 ‘Options -Indexes’ 이 부
분을 삽입하면 된다.

안전한 메일 관리법

센드메일에서 한번에 보낼 수 있는 메일 용량은 /etc/mail /send
mail .cf 파일에서 MaxMessageSize 부분에서 다음과 같이 주석을 제거하
고 바이트 단위로 설정을 해줄 수 있다. 받는 메일 계정의 용량은 Mlocal
부분에서 M=1000000 부분에서 바이트 단위로 제한량을 적는다.

MaxMessageSize=1000000

relay를 막는 방법도 있지만 그건 외부에서 로컬 서버를 SMTP로 사용하지
못하도록만 할 수 있으며 iptables를 이용하면 로컬 서버에서 보내는 메일
에 대해 제한이 가능하다.

# iptables -A OUTPUT -p tcp --syn --dport 25 -j DROP

-A 기존의 iptable에 추가
-p 프로토콜
-dport 포트 넘버
로컬에서 외부로 보내는 메일이라면 remote의 25번 포트로 접속이 되므로
OUTPUT 패킷 중 목적지 포트가 25번인 패킷만 drop 한다. 메일 송수신은
tcp이므로 --syn을 추가하지 않을 경우에는 3 way-handshaking에 의해 메
일을 받을 수도 없게 되므로 반드시 --syn을 추가해야 한다. 보내는 메일
은 일단 메일큐 디렉토리에 저장된 후 발송되므로 메일큐 디렉토리를 삭제
하거나 다른 이름으로 변경하면 메일을 발송할 수 없게 된다.

/etc/mail/access 파일에서 Relay 여부를 설정한다.

localhost RELAY

변경한 후 적용하려면 다음과 같이 실행해 준다. 또는 인증 기능(SMTP
AUTH)이 지원되는 최신 버전의 센드메일을 사용한다.

# makemap hash /etc/mail/access < /etc/mail/access

간단한 방법으로 다음과 같이 텔넷으로 센드메일 포트인 25번으로 접속해
보면 알 수 있다

# telnet jimmy.tt.co.kr 25

가상 계정을 이용해서 해결할 수 있다. 아웃룩에서 jhk라는 계정을 설정하
면 jhk at jungheekim.co.kr, webmaster@jungheekim.
co.kr로 오는 메일을 모
두 받아 볼 수 있다.

# vi /etc/mail/virtusertable
webmaster at jungheekim.co.kr jhk(jhk계정에
webmaster라는 계정이 가상계
정으로 설정)

해외에 출장이 잦은 사용자가 메일을 자신이 사용하는 웹메일로 포워딩해
달라고 하고, 회사에 돌아와서도 포워딩된 메일을 아웃룩에서 다시 받아보
길 원한다면 다음과 같이 한다. 해당 사용자의 홈디렉토리 밑에 .forward
파일을 만들어서 이메일 주소를 입력하고 자신의 계정에는 \를 추가해 주
어야 루프를 막을 수 있다.

vi ~junghee/.forward
sitsme75 at hanmail.net, \junghee.kim at tt.co.kr

메일을 확인할 수 없는 상황일 때, 메일 수신 후 자동으로 미리 작성되어
있는 메시지를 보낼 수 있는 방법(즉 자동응답 메일 작성 방법)은 자신의
홈디렉토리에 “.procmailrc” 파일을 만들고 다음의 내용을 입력한다.

-------------------------------------------
:0 h c
* !^FROM_DAEMON
* !^X-Loop: YOUR@EMAIL
| (formail -r -A"Precedence: junk" \
-I"From: YOUR_NAME " \
-A"X-Loop: YOUR@EMAIL
cat $HOME/autoreply.txt) | $SENDMAIL -t
--------------------------------------------
그리고 ‘autoreply.txt’ 파일에 답변 글을 작성하면 그 내용이 자동 답
변된다.

아웃룩에서 메일을 받아보려고 하는데, POP3가 다운되어 반응하지 않을
때 다음과 같이 조정한다. inetd는 기본적으로 1분에 fork 할 수 있는 인
스턴스가 40으로 제한되어 있으므로 이 값을 늘려줘야 한다. POP3 부분에
서 nowait.200이나 적절한 수만큼 늘려주면 된다. nowait 뒤에 반드시 .
(점)을 찍고 허용할 만큼의 POP 데몬의 수를 입력한다. 이후 inetd를 재시
작하면 적용된다.


A # vi /etc/inetd.conf
# Pop and imap mail services et al
#pop-2 stream tcp nowait root /usr/sbin/tcpd ipop2d
pop-3 stream tcp nowait root /usr/sbin/tcpd ipop3d
#imap stream tcp nowait root /usr/sbin/tcpd imapd


철통 보안 관리

① 현재 서버에서 사용하지 않고, 보안상 취약점이 있는 데몬에 대해 서비
스를 중지한다.
② TCP Wrapper와 ipchains를 이용한다. 커널 2.4에서는 iptables를 이용
해 각 서비스에 대해서 접속을 허락하거나, 제한한다.
③ 섀도우 패스워드를 반드시 이용한다.
④ su 권한의 사용을 특정 사용자만 가능하도록 정의한다.
⑤ 원격에서 루트 권한으로 접속할 수 없도록 한다.
⑥ 지속적으로 패치한다.


echo 1> /proc/sys/net/ipv4/icmp_echo_ignore_all

다시 응답하게 하려면 다음과 같이 실행하면 된다.

echo 0> /proc/sys/net/ipv4/icmp_echo_ignore_all

보통 백도어 파일은 rm 명령으로도 삭제되지 않는다. 속성이 있을 경우 다
음과 같이 삭제 한다.

# lsattr /usr/sbin/in.fingerd
lsattr 1.12, 9-Jul-98 for EXT2 FS 0.5b, 95/08/09
-----a-- /usr/sbin/in.fingerd
==> a 속성이 있음을 확인

chattr -a /usr/sbin/in.fingerd
chattr 1.12, 9-Jul-98 for EXT2 FS 0.5b, 95/08/09
==> -a로 속성을 해제

# lsattr /usr/sbin/in.fingerd
lsattr 1.12, 9-Jul-98 for EXT2 FS 0.5b, 95/08/09
-------- /usr/sbin/in.fingerd
==>해제


lpd는 내부와 원격 프린트 작업을 수행하는 BSD 라인 프린터 데몬이다.
lpd 데몬의 접근 권한을 가지고 있는 내부 시스템이나 원격 시스템의 사용
자가 특별히 변형된 불완전한 프린트작업을 요청하고 이어서 프린터 큐의
디스플레이를 요청하게 되면 해당 시스템에 버퍼 오버플로우를 일으킬 수
있다. 결국 관리자 권한으로 내부 시스템에 공격 코드를 실행시킬 수 있
게 된다. 따라서 패치를 해주거나 서비스를 하지 않는다면 데몬을 중지하
는 것이 좋다.

BIND 4.x, 8.x에서 문제가 검출되었다. BIND 8 버전에서는 트랜잭션 시그
너쳐(TSIG) 핸들링 코드에 버퍼오버플로우 취약점을 포함하고 있다.
유효한 키를 포함하지 않는 TSIG를 발견하는 경우 BIND 8 버전에서는 에러
응답을 보내기 위한 코드를 실행하게 되며, 이때 발생하는 변수 초기화 방
식의 차이에 의해 해당 취약점이 발생하게 된다. DNS 시스템에 대한 요청
접근만으로 해당 취약점을 발생시킬 수 있으므로 이로 인한 위험성은 크
게 된다.
BIND 4 버전에서는 nslookupComplain( ) 내부에 있는 문자 배열(syslog
를 위한 에러 메시지 작성 버퍼)에 대해 버퍼 오버플로우 취약점을 포함하
고 있다. 특수한 포맷 형태를 가진 쿼리를 전송함으로써 해당 취약점을 발
생시킨다.
또한 nslookupComplain( ) 내부에 있는 문자 배열(syslog를 위한 에러 메
시지 작성 버퍼)에 대해 입력 검증(input validation) 취약점을 포함하고
있다. 이것은 특수한 포맷 형태를 가진 쿼리를 전송함으로써 입력 검증 취
약점을 발생시킨다.
BIND 4,8 버전에서는 해당 서버가 쿼리를 처리하는 동안 정보가 누출
(information leak)될 수 있는 취약점을 포함하고 있다. 특수한 포맷 형태
를 가진 쿼리 전송을 통해 공격자가 프로그램 스택에 접근할 수 있게 함으
로써 해당 취약점을 발생시킨다
해결책은 BIND 버전은 8.2.3 이상이나 9.1버전으로 업그레이드하는 것이
다. 이것은 해결책이 아니라 시스템 관리자가 반드시 해야 할 일이다.

장애 발생시 복구

대부분 정전이 발생한 후에도 시스템은 정상적으로 부팅되며 파일시스템
도 자동으로 check하지만 간혹 관리자가 수동으로 해주어야 하는 경우가
발생한다. 리눅스가 다운 되었을때 보통 Power OFF를 하는데, 이때 문제
가 발생할 수 있으므로 Magic SysRq라는 것을 이용하여 안전하게 재부팅하
는 방법을 이용한다.
Magic SysRq key란 시스템의 제어가 불가능한 상태(일반적으로 ‘다운’되
었다고 한다)에서도 제어를 가능하게 해주므로 커널 컴파일시 Kernel
hacking ---> [*] Magic SysRq key를 체크해야 한다. Magic SysRq key를
사용하려면 다음과 같이 /proc/sys/kernel /sysrq 값을 1로 만들어야 한
다.

# echo 1 > /proc/sys/kernel/sysrq
lilo: linux init=/bin/sh

그러면 커널이 뜨고 나서 바로 shell prompt ‘#’가 나타난다. 이때에는
filesystem도 read only로 마운트 되고, 동작하는 deamon process도 전혀
없는 상태가 된다. 그 상태에서 수동으로 모든 파일 시스템을 체크한다.

# fsck [-t ext2] 장치명
# e2fsck 장치명

위의 명령 사용시 문제가 생긴 블록의 수정 여부를 묻게 되는데 ‘y’를
선택하고 만약 수정여부를 묻는 질문이 많다면 -y 옵션을 사용하여 자동으
로 ‘y’를 선택하게 할 수 있다.

# e2fsck -y 장치명

Ctrl-Alt-Del로 리부팅하면 아주 심하게 깨지거나, 디스크에 이상이 있지
않는 한 복구가 된다.
2005/06/27 18:24 2005/06/27 18:24
ftp에서 상위디렉토리막은 경우 특정디렉토리 binding

proftpd의 proftpd.conf에서

DefaultRoot ~ 을 지정하여 특정 그룹의 상위
디렉토리을 막거나 특정디렉토리만 허용할수있게 할수
있습니다. 아마 다들 아시는 내용이실듯합니다.

하지만 이 경우 문제점이 있는 것이 상위을 디렉토리을
막아놓은 유저의 홈디렉토리에 상위의 다른곳을 공유
해야할 경우 방법이 없다는 것이죠..당연히 링크을 걸어
도 자신의 홈에 최상위로 인식하기때문에 되지않을겁니다.

이런때 root의 권한을 가진 사람이 해줄수있는 방법이 있습니다.

바로 mount명령을 이용을 하면 됩니다.


mount --bind /backup/alluser/ /home/test/alluser

물론 /home/userhome/alluser 라는 디렉토리가 존재을 해야겠죠.

이렇게 하면 test라는 계정을 가진 소유자는 최상위
디렉토리밑에 존재하는 /backup/alluser 라는 디렉토리을 같이
공유을 할수있게 되죠...
2005/06/27 18:23 2005/06/27 18:23
리눅스를 사용하다 보면 용량이 부족하여 하드디스크를 추가해야할 상황들이 생길수 있습니다.

자 아래에 방법을 한번 따라 해보도록 하지요?
우선, 새로운 디스크를 접속하고 Linux를 부팅을 합니다. 추가한 디스크를 /dev/hdb라 하며, 다음과 같이 fdisk 커맨드를 실행해서 필요한 용량의 linux 파티션을 만듭니다.

# fdisk /dev/hdb

여기서는 새로운 파티션 /dev/hdb1 을 만들었다고 하고 설명을 계속하겠습니다. 이 파티션에 ext2 파일 시스템을 구축합니다.

# mke2fs /dev/hdb1

이용하기 전에 fsck를 실행해서 파일 시스템을 검사합니다.

# fsck /dev/hdb1

파일시스템에 문제가 없다면 /disk2 (사용자에 맞게 설정합니다.)라는 마운트 포인트를 만들어 /dev/hdb1을 /disk2에 마운트합니다.

#mkdir /disk2
#mount -t ext2 /dev/hdb1 /disk

마지막으로 /etc/fstab에 다음의 행을 추가해서 부팅시에 /dev/hdb1이 마운트되록 합니다.

# vi /etc/fstab
/dev/hdb1 /disk2 ext2 default 1 1

이제 다시 부팅하시면 하드디스크2를 인식하실 겁니다.

수고하세요
2005/06/27 18:23 2005/06/27 18:23
1. 웹 페이지 로딩시간 확인
#time -pa lynx -source http://www.gwise.com > /dev/null
real 0.74
user 0.16
sys 0.09
-------------
실제 접속시간 : 0.74-(0.16+0.09)=0.49초

2. 아파치 벤치 마킹
#man ab 사용법 보기
-n requests 요청을 수행할 개수
-c concurrency 요청을 만들 개수로 동시 사용자 개념으로 이해하면 되겠다.
-v verbosity 얼마나 자세한 정보를 화면에 출력해 줄 것인지 결정
-w HTML 문서형식으로 테이블로 만들어 결과를 화면에 출력
-k HTTP 프로토콜의 지속연결 (KeepAlive) 기능을 사용

#./ab -n 100 -c 10 http://www.gwise.com:80/
10 명의 유저가 동시에 http://www.gwise.com/index.html 을 요청하는 것을 모의 실험.
각각의 시뮬레이트 유저는 요청을 10 번씩 하게 됩니다

# ab -n 1500 -c 50 http://www.apache.kr.net:80/
요청을 30 x 50 (50 명의 사용자가, 각각 30 번의 요청)

Requests per second: 80.48
초당 80.48개를 요청 했음.

'MaxRequestsPerChild’ 는 메모리 누수현상(?) 등이 발생하지 않는다면 가능한 이 값을 높게 설정하시고요(파라미터의 값을 0 으로 설정해 무한대로 하실수도 있습니다) StartServers’ 는 프로세스가 active 되어 있는 경우가 적을 경우 값을 낮게 설정하시고, 접속량이 아주 많을 경우는 MaxClients 에 가깝게 조절하시기 바라며, MaxSpareServers 를 MaxClients 와 같게 설정합니다. MaxClients 는 너무 낮게 설정하지 않도록 주의하시기 바라며, 그렇다고 또 너무 크게 잡으셔도 안됩니다


3. 웹 서버 삽질 막기
BrowserMatch "WebZip" go_out
BrowserMatch "Teleport" go_out
BrowserMatch "GetRight" go_out



....
Deny from env=go_out


4. 아파치 튜닝
일반 서버에서는 다른것은 그냥 Default 값으로 둔다.
(대형 서버의 경우 말고는 특히 쓸 일어 없을 것이다.)

증가 시킬 경우 배수로 한다. 꼭 이렇게 해야 한다가 아니라
이렇게 하면 좋다.

Timeout 300
클라이언트의 요청에 의해서 Server와 연결 되었을때
클라이언트와 서버간의 아무런 메시지가 발생하지 않았을때
오류로 처리하는 시간
네트워크 속도가 나쁠수록 수치값을 높게 한다.

KeepAlive on
지속적인 접속, 즉 서버 연결에 대하여 한번 이상의 요청을 허용 여부.

MaxKeepAliveRequests 100
클라이언트가 접속된 시간동안 아파치 서버에 요청할 수 있는 처리 process 개수

StartServers 5 X ? =20 -> 초반에 뜰 process 그 이상 그이하의 의미도 없다.
MinSpareServers 5 X ? =20 -> Spare 프로세스가 이것 이하 일때 끌어 올려 준다.
MaxSpareServers 10 X ? =40 -> Spare 프로세스가 이것 이상 일때 진정(?)시켜 준다.
말 그대로 Spare.... 언제 있을지 모를 요청에 대해서 컴퓨터 스스로가
조절해 준다.

MaxClients 150
클라이언트들이 동시에 최대로 접속했을때 가능한 최대 서버이 수를 지정.
Ulimit -a ~~~ max process...이 수치 이상 증가 못함.
httpd.h
HARD_SERVER_LIMIT=250 조정해서 다시 컴파일 가능

MaxClient 150 -> 동시에 떠 있을수 있는 최대 process
더 많은 수를 원할시 httpd.h 소스 파일의
HARD_SERVER_LIMIT 값을 수정 한 다음 다시 컴파일 해야 한다.

#ulimit -a
core file size (blocks) 0
data seg size (kbytes) unlimited
file size (blocks) unlimited
max memory size (kbytes) unlimited
stack size (kbytes) 8192
cpu time (seconds) unlimited
max user processes 2048
pipe size (512 bytes) 8
open files 1024
virtual memory (kbytes) 2105343
-----------------------
위의 max user processes 의 수를 초과 할 수 없다.

MaxRequestPerChild 100
한 프로세스가 몇 번의 서비스를 하고 소멸될 것인지 정한다.
M$계열에서는 별 의미가 없으므로 0을 한다.
하지만 Unix 계열은 0을 사용하지 않는 것이 좋다.

가장 중요한 것은Timeout 설정입니다. 위에서 keep-alive 를 설정해 놓은
경우, 하나의 connection에서 계속해서 다음 request를 처리할 수 있기 때문에 효율적
이라고 하지만, 실제로는 그렇지 않습니다. keep-alive 를 허용하고 그 timeout을
5초로만 설정해도, 하나의 request를 처리한 후 적어도 5초동안은 그 httpd가 다른
작업을 하지 못하고 다음 request를 기다리게 됩니다.

보통 웹브라우저들은 서버로 동시에 4개의 connection을 만들게 됩니다. 한 페이지를
보는데 이미지 등등 해서 보통 4개의 connection을 만드는 것은 기본이죠. 이렇게 되면
httpd가 100개 떠 있다고 해도, 실제로는 동시에 25명의 방문자밖에 처리하지 못합니다.

그리고 keep-alive timeout이 5초인 경우, 한 명의 방문자를 처리한 후 적어도 5초동안은
계속해서 기다리면서 httpd가 놀게 됩니다.(그렇다고 해서 httpd의 수를 늘여주면 앞의
문제 때문에 load가 몰릴 때 순간적으로 부하가 지나치게 많이 걸리게 됩니다. 어떤
request는 수초가 지난 후 답을 받는 등 quality of service가 많이 떨어지죠.)

결국 한 명의 방문자를 처리하는데 4개의 httpd가 5초동안 작업한다는 뜻이고, 100개의
httpd를 띄워봐야 1초에 5명의 방문자밖에 처리하지 못하는 셈입니다. ( 1 명 / 5 sec /
4 httpd = 5 / 1 sec / 100 httpd )

그래서 검색엔진 서비스 등 traffic이 많은 사이트에서는 keep-alive 옵션을 반드시 꺼
놓게 됩니다. 그리고 connection timeout도 상당히 짧게 설정해 놓죠. 4~5초 이내로 말입니다


5. 아피치 튜닝-2(로그기록 로테이트로)
/home/apache/conf/httpd.conf
CustomLog /home/apache/logs/access_log common
TransferLog "|/home/apache/bin/rotatelogs /home/apache/logs/access_log 86400"
TransferLog "|/home/apache/bin/rotatelogs /home/apache/logs/error_log 86400"
--------------
24시간 마다 로그 화일을 갱신해 준다.
24X60X60=86400초

6. 아파치 에러 메시지 바꾸기
httpd.conf
Customizable error response (Apache style)
2) local redirects
ErrorDocument 404 /cgi-bin/missing404.pl

missing404.pl
---------------
#!/usr/bin/perl
print<<"(END_HTML)";
Content-type: text/html\n\n
요청한 URL 이 없습니다.






요청하신 http://www.gwise.com$ENV{'REQUEST_URI'} 이

존재 하지 않습니다.





서버관리자
에게 문의 바랍니다.



(END_HTML)
exit;
---------------

7. 아파치 에러 코드
HTTP 1.1 status codes [TOP]

100 : Continue
101 : Switching protocols
200 : OK, 에러없이 전송 성공
201 : Created, POST 명령 실행 및 성공
202 : Accepted, 서버가 클라이언트 명령을 받음
203 : Non-authoritative information, 서버가 클라이언트 요구 중 일부만 전송
204 : No content, 클라언트 요구을 처리했으나 전송할 데이터가 없음
205 : Reset content
206 : Partial content
300 : Multiple choices, 최근에 옮겨진 데이터를 요청
301 : Moved permanently, 요구한 데이터를 변경된 임시 URL에서 찾았음
302 : Moved temporarily, 요구한 데이터가 변경된 URL에 있음을 명시
303 : See other, 요구한 데이터를 변경하지 않았기 때문에 문제가 있음
304 : Not modified
305 : Use proxy
400 : Bad request, 클라이언트의 잘못된 요청으로 처리할 수 없음
401 : Unauthorized, 클라이언트의 인증 실패
402 : Payment required, 예약됨
403 : Forbidden, 접근이 거부된 문서를 요청함
404 : Not found, 문서를 찾을 수 없음
405 : Method not allowed, 리소스를 허용안함
406 : Not acceptable, 허용할 수 없음
407 : Proxy authentication required, 프록시 인증 필요
408 : Request timeout, 요청시간이 지남
409 : Conflict
410 : Gone, 영구적으로 사용할 수 없음
411 : Length required
412 : Precondition failed, 전체조건 실패
413 : Request entity too large,
414 : Request-URI too long, URL이 너무 김
415 : Unsupported media type
500 : Internal server error, 내부서버 오류(잘못된 스크립트 실행시)
501 : Not implemented, 클라이언트에서 서버가 수행할 수 없는 행동을 요구함
502 : Bad gateway, 서버의 과부하 상태
503 : Service unavailable, 외부 서비스가 죽었거나 현재 멈춤 상태
504 : Gateway timeout
505 : HTTP version not supported
2005/06/27 18:23 2005/06/27 18:23
원격지의 OS 및 각종 데몬에 대한 버전 정보를 숨기거나 위조하는 방법에 대한
설명입니다.
주로 소스를 수정하거나 config 에서 지원이 되는 경우
config 파일에서 설정하는 방법도 있습니다.
참고하시기 바랍니다.

감사합니다.


### Apache 웹서버
(1) 소스 수정
src/include/httpd.h :
#define SERVER_BASEVERSION "Apache/[x.x.x.]"

(2) Conf 설정
httpd.conf 파일에서
ServerTokens 설정

ServerTokens Prod[uctOnly]
--> Server: Apache
ServerTokens Min[imal]
--> Server: Apache/1.3.0
ServerTokens OS
--> Server: Apache/1.3.0 (Unix)
ServerTokens Full (or not specified)
--> Server: Apache/1.3.0 (Unix) PHP/3.0 MyMod/1.2

### Proftpd

Conf 설정
proftpd.conf 파일에서
ServerIdent on "[x.x.x]"

### Sendmail
(1) 소스 수정
sendmail/version.c
char Version[] = "[x.x.x]";
(2) Conf 설정
/etc/sendmail.cf:
# SMTP initial login message
O SmtpGreetingMessage=$j [x.x.x]


### Bind
Conf 설정
/etc/named.conf 파일에서
options {
directory "/var/named";
version "x.x.x";
};


### SSH1/OpenSSH
소스 수정
version.h 파일에서
#define SSH_VERSION "[x.x.x]"

### SSH2
소스 수정
apps/ssh/ssh2version.h 파일에서
#define SSH2_VERSION "[x.x.x]"

### IMAP (imapd,ipop2d,ipop3d)
소스 수정
src/imapd/imapd.c 파일에서 char *version = "[x.x.x]";
src/ipopd/ipop2d.c 파일에서 char *version = "[x.x.x]";
src/ipopd/ipop3d.c 파일에서 char *version = "[x.x.x]";

### O.S.-Guessing Linux (2.2.x)
kernel patch: KOSF (Kernel Operation System Faker)
http://linuxsecurity.com.br/tools/patch/linux/kosf.tar.gz

### O.S.-Guessing Linux (2.4.x)
http://ippersonality.sourceforge.net/
CONFIG_IP_NF_PERS patch.
ipt_PERS http://ippersonality.sourceforge.net/doc/ippersonality-en.html

### Microsoft Windows NT registry
http://www.linuxsecurity.com.br/info/microsoft/obscurity.nt.txt
2005/06/27 18:22 2005/06/27 18:22
1. 들어가는 말

아파치로 웹사이트를 운영하다보면 로그 파일을 처리하지 못해 고민하는 경우
를 흔히 보게 됩니다. 어떻게 분석해야 하는지. 어떻게 관리해야 하는지 등
등..
저는 로그 파일 처리 방법을 cronolog를 애용하고 있습니다.
다양한 방법이있겠지만. cronolog가 하나의 대안이 될 수 있기에 여기에 소개
합니다.

cronolog는 아파치의 logrotate를 대신하는 유틸입니다.
두 유틸의 차이점은 logrotate는 특정 시간 간격으로 로그 파일을 교체해주지
만 cronolog는 yymmdd 에 따라 로그파일을 분할한다는 점입니다.

예를 들어 access_log.010920, access_log.010921 등이 가능해집니다.
(IIS에서는 기본으로 제공하는 기능이긴 하지만요..)

일/월/년 단위로 로그를 자르기 때문에 보관하기도 편하고 로그 분석할때도 편
합니다. 로그 파일이 무작정 커질일도 없고요..

2. 설치

필요한것:
apache (당연하겠죠)
cronolog http://www.ford-mason.co.uk/resources/cronolog/
압축푸는 프로그램, 컴파일러

다운받아서 컴파일하고 설치하면됩니다.
/usr/local/sbin/cronolog에 깔릴겁니다.

이제 httpd.conf 를 수정합니다.

3. 설정 & 예제

설정: TransferLog "|/usr/local/sbin/cronolog /www/logs/%Y/%m/%
d/access.log"
결과:
/www/logs/2001/01/01/access.log
/www/logs/2001/01/02/access.log

대문자 Y 를 소문자 y로 고쳤습니다.
설정: TransferLog "|/usr/local/sbin/cronolog /www/logs/%y/%m/%
d/access.log"
결과:
/www/logs/01/01/01/access.log
/www/logs/01/01/02/access.log

%d를 지우면 월단위로 남깁니다.
설정: TransferLog "|/usr/local/sbin/cronolog /www/logs/%y/%m/access.log"
결과:
/www/logs/01/01/access.log
/www/logs/01/02/access.log

한 디렉토리에 저장하는거도 가능합니다.
설정: TransferLog "|/usr/local/sbin/cronolog /www/logs/access.%Y%m%d"
결과:
/www/logs/access.20010101
/www/logs/access.20010102

비슷한거
설정: TransferLog "|/usr/local/sbin/cronolog /www/logs/www%Y%m%d.log"
결과:
/www/logs/www20010101.log
/www/logs/www20010102.log

access_log 로 심볼릭 링크를 걸수도 있습니다.
access_log에 심볼릭링크는 주기적으로 바뀌어서 지금 사용하는 로그파일이 됩
니다.
TransferLog "|/usr/local/sbin/cronolog --
symlink=/www/logs/access_log /www/logs/www%y%m%d.log"
/www/logs/access_log -> /www/logs/www20010102.log
/www/logs/www20010101.log
/www/logs/www20010102.log
로그분석 프로그램에서 로그파일을 지정해야 하는 하는 경우에 (예,
webalizer) access_log 를 지정하면 해당하는 날짜의 로그파일을 가리키겠
죠...

4. 본격 활용

문제:
아파치로 웹사이트를 운영하고 있는데 로그 분석을 해서 방문자 현황을 보고
싶다. 그리고 지나간 로그 파일을 날짜별로 정리해서 압축해서 보관하고 싶
다.

해결:
cronolog를 이용해 로그를 분할 저장합니다. 이때 심볼릭링크를 반드시 해야합
니다.
TransferLog "|/usr/local/sbin/cronolog --
symlink=/www/logs/access_log /www/logs/www%y%m%d.log"

그러면 로그는 이렇게 저장됩니다.
/www/logs/access_log -> /www/logs/www20010102.log
/www/logs/www20010101.log
/www/logs/www20010102.log

Webalizer의 conf 파일에서 분석할 로그 파일을 /www/logs/access_log 로 지정
합니다. 물론 history 보관 옵션을 on 해야 합니다.

crontab 파일을 열어 매일 23시 59분에 webzlizer를 실행하도록 세팅합니다.
성격이 급한 분은 매일/매시/59분으로 세팅해도 무방합니다.

매일 23시 59분에 cron에 의해 webalizer가 실행되며 access_log에 심볼릭링크
된 오늘자 아파치 로그를 분석하고 history에 저장합니다.
0시 0분이 되면 (새로운 접속이 있으면) 아파치(cronolog)는 새로운 날짜의 로
그파일을 만들고 access_log 에는 새로운 파일을 링크걸게 됩니다.
다시 23시 59분이 되면 cron이 webzlizer를 실행시키고, access_log를 분석하
는데 어제 날짜가 아닌 오늘 날짜의 파일을 분석합니다.

문제:
지나간 로그를 자동으로 압축하고 싶다.

해결:
파일을 압축하는 스크립트를 cron에 등록시켜 사용하면 됩니다.
예를 들면...
find /www/logs -name *.log -mtime +1 -exec gzip {} \;
2005/06/27 18:22 2005/06/27 18:22
도메인정보 수정후 수정내용을 확인시 nslookup으로 해당 정보가 바뀌었는지를 확인합니다.

변경된 정보가 네임서버에 반영될려면 네임서버정보중 ttl값이라는 것이 영향을 미치는데
네임서버에서 이 ttl값이 얼마나 남았는지 확인하는 방법입니다.

먼저 nslookup 콘솔로 들어갑니다.

# nslookup
>

옵션중 debug라는 옵션을 켭니다.

> set debug

querytype을 SOA로 변경합니다.

> set querytype=SOA

도메인정보를 입력합니다.

> kldp.org

Server: ns.gihc.net
Address: 203.235.122.164

;; res_nmkquery(QUERY, kldp.org, IN, SOA)
------------
Got answer:
HEADER:
opcode = QUERY, id = 29106, rcode = NOERROR
header flags: response, want recursion, recursion avail.
questions = 1, answers = 1, authority records = 2, additional = 2

QUESTIONS:
kldp.org, type = SOA, class = IN
ANSWERS:
-> kldp.org
ttl = 913 (913)
origin = ns.nuri.net
mail addr = dnsmaster.gihc.net
serial = 2002090200
refresh = 3600 (1H)
retry = 600 (10M)
expire = 864000 (864000)
minimum ttl = 3600 (1H)
AUTHORITY RECORDS:
-> kldp.org
nameserver = ns.nuri.net
ttl = 176 (176)
-> kldp.org
nameserver = ns2.nuri.net
ttl = 176 (176)
ADDITIONAL RECORDS:
-> ns.nuri.net
internet address = 203.255.112.34
ttl = 44145 (44145)
-> ns2.nuri.net
internet address = 203.255.112.4
ttl = 44164 (44164)

------------
Non-authoritative answer:
kldp.org
ttl = 913 (913)
origin = ns.nuri.net
mail addr = dnsmaster.gihc.net
serial = 2002090200
refresh = 3600 (1H)
retry = 600 (10M)
expire = 864000 (864000)
minimum ttl = 3600 (1H)

Authoritative answers can be found from:
kldp.org
nameserver = ns.nuri.net
ttl = 176 (176)
kldp.org
nameserver = ns2.nuri.net
ttl = 176 (176)
ns.nuri.net
internet address = 203.255.112.34
ttl = 44145 (44145)
ns2.nuri.net
internet address = 203.255.112.4
ttl = 44164 (44164)

위와같이 네임서버에 남은 ttl시간이 표시됩니다. ^^;

언제 바뀔지 기다리지 말고 얼마나 남았는지 확인할수 있습니다.
2005/06/27 18:21 2005/06/27 18:21
File and Disk Tuning
Benchmark performance is often heavily based on disk I/O performace. So getting as much disk I/O as possible is the real key.
Depending on the array, and the disks used, and the controller, you may want to try software raid. It is tough to beat software raid performace on a modern cpu with a fast disk controller.

The easiest way to configure software raid is to do it during the install. If you use the gui installer, there are options in the disk partion screen to create a "md" or multiple-device, linux talk for a software raid partion. You will need to make partions on each of the drives of type "linux raid", and then after creating all these partions, create a new partion, say " /test", and select md as its type. Then you can select all the partions that should be part of it, as well as the raid type. For pure performance, RAID 0 is the way to go.

Note that by default, I belive you are limited to 12 drives in a MD device, so you may be limited to that. If the drives are fast enough, that should be sufficent to get >100 MB/s pretty consistently.

One thing to keep in mind is that the position of a partion on a hardrive does have performance implications. Partions that get stored at the very outer edge of a drive tend to be significantly faster than those on the inside. A good benckmarking trick is to use RAID across several drives, but only use a very small partion on the outside of the disk. This give both consistent performance, and the best performance. On most moden drives, or least drives using ZCAV (Zoned Constant Angular Velocity), this tends to be sectors with the lowest address, aka, the first partions. For a way to see the differences illustrated, see the ZCAV page.

This is just a summary of software RAID configuration. More detailed info can be found elsewhere including the Software-RAID-HOWTO, and the docs and man pages from the raidtools package.



File System Tuning

Some of the default kernel paramaters for system performance are geared more towards workstation performance that file server/large disk io type of operations. The most important of these is the "bdflush" value in /proc/sys/vm/bdflush
These values are documented in detail in /usr/src/linux/Documenation/sysctl/vm.txt.

A good set of values for this type of server is:

echo 100 5000 640 2560 150 30000 5000 1884 2 > /proc/sys/vm/bdflush

(you change these values by just echo'ing the new values to the file. This takes effect immediately. However, it needs to be reinitilized at each kernel boot. The simplest way to do this is to put this command into the end of /etc/rc.d/rc.local)

Also, for pure file server applications like web and samba servers, you probably want to disable the "atime" option on the filesystem. This disabled updating the "atime" value for the file, which indicates that the last time a file was accessed. Since this info isnt very useful in this situation, and causes extra disk hits, its typically disabled. To do this, just edit /etc/fstab and add "notime" as a mount option for the filesystem.

for example:

/dev/rd/c0d0p3 /test ext2 noatime 1 2

With these file system options, a good raid setup, and the bdflush values, filesystem performace should be suffiecent.

The disk i/o elevators is another kernel tuneable that can be tweaked for improved disk i/o in some cases.


SCSI Tuning

SCSI tuning is highly dependent on the particular scsi cards and drives in questions. The most effective variable when it comes to SCSI card performace is tagged command queueing.
For the Adaptec aic7xxx seriers cards (2940's, 7890's, *160's, etc) this can be enabled with a module option like:


aic7xx=tag_info:{{0,0,0,0,}}

This enabled the default tagged command queing on the first device, on the first 4 scsi ids.


options aic7xxxaic7xxx=tag_info:{{24.24.24.24.24.24}}

in /etc/modules.conf will set the TCQ depth to 24
You probably want to check the driver documentation for your particular scsi modules for more info.


Disk I/O Elevators

On systems that are consistently doing a large amount of disk I/O, tuning the disk I/O elevators may be useful. This is a 2.4 kernel feature that allows some control over latency vs throughput by changing the way disk io elevators operate.
This works by changing how long the I/O scheduler will let a request sit in the queue before it has to be handled. Since the I/O scheduler can collapse some request together, having a lot of items in the queue means more can be cooalesced, which can increase throughput.

Changing the max latency on items in the queue allows you to trade disk i/o latency for throughput, and vice versa.

The tool "/sbin/elvtune" (part of util-linux) allows you to change these max latency values. Lower values means less latency, but also less thoughput. The values can be set for the read and write queues seperately.

To determine what the current settings are, just issue:

/sbin/elvtune /dev/hda1

substituting the approriate device of course. Default values are 8192 for read, and 16384 for writes.
To set new values of 2000 for read and 4000 for example:

/sbin/elvtune -r 2000 -w 4000 /dev/hda1

Note that these values are for example purposes only, and are not recomended tuning values. That depends on the situation.
The units of these values are basically "sectors of writes before reads are allowed". The kernel attempts to do all reads, then all writes, etc in an attempt to prevent disk io mode switching, which can be slow. So this allows you to alter how long it waits before switching.

One way to get an idea of the effectiveness of these changes is to monitor the output of `isostat -d -x DEVICE`. The "avgrq-sz" and "avgqu-sz" values (average size of request and average queue length, see man page for iostat) should be affected by these elevator changes. Lowering the latency should cause the "avqrq-sz" to go down, for example.

See the elvtune man page for more info. Some info from when this feature was introduced is also at Lwn.net

This info contributed by Arjan van de Ven.


Network Interface Tuning

Most benchmarks benifit heavily from making sure the NIC's in use are well supported, with a well written driver. Examples include eepro100, tulip's, newish 3com cards, and acenic and sysconect gigabit cards.
Making sure the cards are running in full duplex mode is also very often critical to benchmark performace. Depending on the networking hardware used, some of the cards may not autosense properly and may not run full duplex by default.

Many cards include module options that can be used to force the cards into full duplex mode. Some examples for common cards include


alias eth0 eepro100
options eepro100 full_duplex=1
alias eth1 tulip
options tulip full_duplex=1

Though full duplex gives the best overall performance, I've seen some circumstances where setting the cards to half duplex will actually increase thoughput, particulary in cases where the data flow is heavily one sided.

If you think your in a situation where that may help, I would suggest trying it and benchmarking it.


TCP tuning

For servers that are serving up huge numbers of concurent sessions, there are some tcp options that should probabaly be enabled. With a large # of clients doing their best to kill the server, its probabaly not uncommon for the server to have 20000 or more open sockets.
In order to optimize TCP performace for this situation, I would suggest tuning the following parameters.


echo 1024 65000 > /proc/sys/net/ipv4/ip_local_port_range

Allows more local ports to be available. Generally not a issue, but in a benchmarking scenario you often need more ports available. A common example is clients running `ab` or `http_load` or similar software.
In the case of firewalls, or other servers doing NAT or masquerading, you may not be able to use the full port range this way, because of the need for high ports for use in NAT.

Increasing the amount of memory associated with socket buffers can often improve performance. Things like NFS in particular, or apache setups with large buffer configured can benefit from this.


echo 262143 > /proc/sys/net/core/rmem_max
echo 262143 > /proc/sys/net/core/rmem_default

This will increase the amount of memory available for socket input queues. The "wmem_*" values do the same for output queues.
Note: With 2.4.x kernels, these values are supposed to "autotune" fairly well, and some people suggest just instead changing the values in:

/proc/sys/net/ipv4/tcp_rmem
/proc/sys/net/ipv4/tcp_wmem

There are three values here, "min default max".
These reduce the amount of work the TCP stack has to do, so is often helpful in this situation.

echo 0 > /proc/sys/net/ipv4/tcp_sack
echo 0 > /proc/sys/net/ipv4/tcp_timestamps




File Limits and the like

Open tcp sockets, and things like apache are prone to opening a large amount of file descriptors. The default number of available FD is 4096, but this may need to be upped for this scenario.
The theorectial limit is roughly a million file descriptors, though I've never been able to get close to that many open.

I'd suggest doubling the default, and trying the test. If you still run out of file descriptors, double it again.

For example:


echo 128000 > /proc/sys/fs/inode-max
echo 64000 > /proc/sys/fs/file-max

and as root:
ulimit -n 64000

Note: On 2.4 kernels, the "inode-max" entry is no longer needed.

You probabaly want to add these to /etc/rc.d/rc.local so they get set on each boot.

There are more than a few ways to make these changes "sticky". In Red Hat Linux, you can you /etc/sysctl.conf and /etc/security/limits.conf to set and save these values.

If you get errors of the variety "Unable to open file descriptor" you definately need to up these values.

You can examine the contents of /proc/sys/fs/file-nr to determine the number of allocated file handles, the number of file handles currently being used, and the max number of file handles.


Process Limits

For heavily used web servers, or machines that spawn off lots and lots of processes, you probabaly want to up the limit of processes for the kernel.
Also, the 2.2 kernel itself has a max process limit. The default values for this are 2560, but a kernel recompile can take this as high as 4000. This is a limitation in the 2.2 kernel, and has been removed from 2.3/2.4.

The values that need to be changed are:

If your running out how many task the kernel can handle by default, you may have to rebuild the kernel after editing:


/usr/src/linux/include/linux/tasks.h

and change:

#define NR_TASKS 2560 /* On x86 Max 4092, or 4090 w/APM
configured.*/

to
#define NR_TASKS 4000 /* On x86 Max 4092, or 4090 w/APM
configured.*/

and:
#define MAX_TASKS_PER_USER (NR_TASKS/2)

to
#define MAX_TASKS_PER_USER (NR_TASKS)

Then recompile the kernel.


also run:

ulimit -u 4000

Note: This process limit is gone in the 2.4 kernel series.


Threads

Limitations on threads are tightly tied to both file descriptor limits, and process limits.

Under Linux, threads are counted as processes, so any limits to the number of processes also applies to threads. In a heavily threaded app like a threaded TCP engine, or a java server, you can quickly run out of threads.

For starters, you want to get an idea how many threads you can open. The `thread-limit` util mentioned in the Tuning Utilities section is probabaly as good as any.

The first step to increasing the possible number of threads is to make sure you have boosted any process limits as mentioned before.

There are few things that can limit the number of threads, including process limits, memory limits, mutex/semaphore/shm/ipc limits, and compiled in thread limits. For most cases, the process limit is the first one to run into, then the compiled in thread limits, then the memory limits.

To increase the limits, you have to recompile glibc. Oh fun!. And the patch is essentially two lines!. Woohoo!


--- ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h.akl Mon Sep 4
19:37:42 2000
+++ ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h Mon Sep 4
19:37:56 2000
@@ -64,7 +64,7 @@
/* The number of threads per process. */
#define _POSIX_THREAD_THREADS_MAX 64
/* This is the value this implementation supports. */
-#define PTHREAD_THREADS_MAX 1024
+#define PTHREAD_THREADS_MAX 8192

/* Maximum amount by which a process can descrease its asynchronous I/O
priority level. */
--- ./linuxthreads/internals.h.akl Mon Sep 4 19:36:58 2000
+++ ./linuxthreads/internals.h Mon Sep 4 19:37:23 2000
@@ -330,7 +330,7 @@
THREAD_SELF implementation is used, this must be a power of two and
a multiple of PAGE_SIZE. */
#ifndef STACK_SIZE
-#define STACK_SIZE (2 * 1024 * 1024)
+#define STACK_SIZE (64 * PAGE_SIZE)
#endif

/* The initial size of the thread stack. Must be a multiple of PAGE_SIZE.
* */

Now just patch glibc, rebuild, and install it. ;-> If you have a package based system, I seriously suggest making a new package and using it.

Two references on how to do this are Jlinux.org, and Volano.Both describe how to increase the number of threads so Java apps can use them.


NFS

A good resource on NFS tuning on linux is the linux NFS HOW-TO. Most of this info is gleaned from there.

But the basic tuning steps include:

Try using NFSv3 if you are currently using NFSv2. There can be very significant performance increases with this change.

Increasing the read write block size. This is done with the rsize and wsize mount options. They need to the mount options used by the NFS clients. Values of 4096 and 8192 reportedly increase performance alot. But see the notes in the HOWTO about experimenting and measuring the performance implications. The limits on these are 8192 for NFSv2 and 32768 for NFSv3

Another approach is to increase the number of nfsd threads running. This is normally controlled by the nfsd init script. On Red Hat Linux machines, the value "RPCNFSDCOUNT" in the nfs init script controls this value. The best way to determine if you need this is to experiment. The HOWTO mentions a way to determin thread usage, but that doesnt seem supported in all kernels.

Another good tool for getting some handle on NFS server performance is `nfsstat`. This util reads the info in /proc/net/rpc/nfs[d] and displays it in a somewhat readable format. Some info intended for tuning Solaris, but useful for it's description of the nfsstat format

See also the tcp tuning info


Apache config

Make sure you starting a ton of initial daemons if you want good benchmark scores.

Something like:

#######
MinSpareServers 20
MaxSpareServers 80
StartServers 32

# this can be higher if apache is recompiled
MaxClients 256

MaxRequestsPerChild 10000

Note: Starting a massive amount of httpd processes is really a benchmark hack. In most real world cases, setting a high number for max servers, and a sane spare server setting will be more than adequate. It's just the instant on load that benchmarks typically generate that the StartServers helps with.
The MaxRequestPerChild should be bumped up if you are sure that your httpd processes do not leak memory. Setting this value to 0 will cause the processes to never reach a limit.

One of the best resources on tuning these values, especially for app servers, is the mod_perl performance tuning documentation.

Bumping the number of available httpd processes

Apache sets a maximum number of possible processes at compile time. It is set to 256 by default, but in this kind of scenario, can often be exceeded.

To change this, you will need to chage the hardcoded limit in the apache source code, and recompile it. An example of the change is below:


--- apache_1.3.6/src/include/httpd.h.prezab Fri Aug 6 20:11:14 1999
+++ apache_1.3.6/src/include/httpd.h Fri Aug 6 20:12:50 1999
@@ -306,7 +306,7 @@
* the overhead.
*/
#ifndef HARD_SERVER_LIMIT
-#define HARD_SERVER_LIMIT 256
+#define HARD_SERVER_LIMIT 4000
#endif

/*

To make useage of this many apache's however, you will also need to boost the number of processes support, at least for 2.2 kernels. See the section on kernel process limits for info on increasing this.


The biggest scalability problem with apache, 1.3.x versions at least, is it's model of using one process per connection. In cases where there large amounts of concurent connections, this can require a large amount resources. These resources can include RAM, schedular slots, ability to grab locks, database connections, file descriptors, and others.
In cases where each connection takes a long time to complete, this is only compunded. Connections can be slow to complete because of large amounts of cpu or i/o usage in dynamic apps, large files being transfered, or just talking to clients on slow links.

There are several strategies to mitigate this. The basic idea being to free up heavyweight apache processes from having to handle slow to complete connections.

Static Content Servers

If the servers are serving lots of static files (images, videos, pdf's, etc), a common approach is to serve these files off a dedicated server. This could be a very light apache setup, or any many cases, something like thttpd, boa, khttpd, or TUX. In some cases it is possible to run the static server on the same server, addressed via a different hostname.
For purely static content, some of the other smaller more lightweight web servers can offer very good performance. They arent nearly as powerful or as flexible as apache, but for very specific performance crucial tasks, they can be a big win.


Boa: http://www.boa.org/
thttpd: http://www.acme.com/software/thttpd/
mathopd: http://mathop.diva.nl

If you need even more ExtremeWebServerPerformance, you probabaly want to take a look at TUX, written by Ingo Molnar. This is the current world record holder for SpecWeb99. It probabaly owns the right to be called the worlds fastest web server.


Proxy Usage
For servers that are serving dynamic content, or ssl content, a better approach is to employ a reverse-proxy. Typically, this would done with either apache's mod_proxy, or Squid. There can be several advantages from this type of configuration, including content caching, load balancing, and the prospect of moving slow connections to lighter weight servers.
The easiest approache is probabaly to use mod_proxy and the "ProxyPass" directive to pass content to another server. mod_proxy supports a degree of caching that can offer a significant performance boost. But another advantage is that since the proxy server and the web server are likely to have a very fast interconnect, the web server can quickly serve up large content, freeing up a apache process, why the proxy slowly feeds out the content to clients. This can be further enhanced by increasing the amount of socket buffer memory thats for the kernel. See the section on tcp tuning for info on this.

proxy links

Info on using mod_proxy in conjuction with mod_perl

webtechniques article on using mod_proxy

mod_proxy home page

Squid

Using mod_proxy with Zope

ListenBacklog

One of the most frustrating thing for a user of a website, is to get "connection refused" error messages. With apache, the common cause of this is for the number of concurent connections to exceed the number of available httpd processes that are available to handle connections.
The apache ListenBacklog paramater lets you specify what backlog paramater is set to listen(). By default on linux, this can be as high as 128.

Increasing this allows a limited number of httpd's to handle a burst of attempted connections.

There are some experimental patches from SGI that accelerate apache. More info at:

http://oss.sgi.com/projects/apache/
I havent really had a chance to test the SGI patches yet, but I've been told they are pretty effective.


Samba Tuning

Depending on the type of tests, there are a number of tweaks you can do to samba to improve its performace over the default. The default is best for general purpose file sharing, but for extreme uses, there are a couple of tweaks.
The first one is to rebuild it with mmap support. In cases where you are serving up a large amount of small files, this seems to be particularly useful. You just need to add a "--with-mmap" to the configure line.

You also want to make sure the following options are enabled in the /etc/smb.conf file:


read raw = no
read prediction = true
level2 oplocks = true

One of the better resources for tuning samba is the "Using Samba" book from O'reily. The chapter on performance tuning is available online.



Openldap tuning

The most important tuning aspect for OpenLDAP is deciding what attributes you want to build indexes on.
I use the values:

cachesize 10000
dbcachesize 100000
sizelimit 10000
loglevel 0
dbcacheNoWsync

index cn,uid
index uidnumber
index gid
index gidnumber
index mail

If you add the following parameters to /etc/openldap/slapd.conf before entering the info into the database, they will all get indexed and performance will increase.


SysV shm
Some applications, databases in particular, sometimes need large amounts of SHM segments and semaphores. The default limit for the number of shm segments is 128 for 2.2.
This limit is set in a couple of places in the kernel, and requires a modification of the kernel source and a recompile to increase them.

A sample diff to bump them up:


--- linux/include/linux/sem.h.save Wed Apr 12 20:28:37 2000
+++ linux/include/linux/sem.h Wed Apr 12 20:29:03 2000
@@ -60,7 +60,7 @@
int semaem;
};

-#define SEMMNI 128 /* ? max # of semaphore identifiers */
+#define SEMMNI 512 /* ? max # of semaphore identifiers */
#define SEMMSL 250 /* <= 512 max num of semaphores per id */
#define SEMMNS (SEMMNI*SEMMSL) /* ? max # of semaphores in system */
#define SEMOPM 32 /* ~ 100 max num of ops per semop call */
--- linux/include/asm-i386/shmparam.h.save Wed Apr 12 20:18:34 2000
+++ linux/include/asm-i386/shmparam.h Wed Apr 12 20:28:11 2000
@@ -21,7 +21,7 @@
* Keep _SHM_ID_BITS as low as possible since SHMMNI depends on it and
* there is a static array of size SHMMNI.
*/
-#define _SHM_ID_BITS 7
+#define _SHM_ID_BITS 10
#define SHM_ID_MASK ((1<<_SHM_ID_BITS)-1)

#define SHM_IDX_SHIFT (_SHM_ID_BITS)

Theoretically, the _SHM_ID_BITS can go as high as 11. The rule is that _SHM_ID_BITS + _SHM_IDX_BITS must be <= 24 on x86.

In addition to the number of shared memory segments, you can control the maximum amount of memory allocated to shm at run time via the /proc interface. /proc/sys/kernel/shmmax indicates the current. Echo a new value to it to increase it.

echo "67108864" > /proc/sys/kernel/shmmax

To double the default value.
A good resource on this is Tunings The Linux Kernel's Memory.

The best way to see what the current values are, is to issue the command:

ipcs -l

Ptys and ttys
The number of ptys and ttys on a box can sometimes be a limiting factor for things like login servers and database servers.
On Red Hat Linux 7.x, the default limit on ptys is set to 2048 for i686 and athlon kernels. Standard i386 and similar kernels default to 256 ptys.

The config directive CONFIG_UNIX98_PTY_COUNT defaults to 256, but can be set as high as 2048. For 2048 ptys to be supported, the value of UNIX98_PTY_MAJOR_COUNT needs to be set to 8 in include/linux/major.h

With the current device number scheme and allocations, the maximum number of ptys is 2048.


Benchmarks
Lies, damn lies, and statistics.
But aside from that, a good set of benchmarking utilities are often very helpful in doing system tuning work. It is impossible to duplicate "real world" situations, but that isnt really the goal of a good benchmark. A good benchmark typically tries to measure the performance of one particular thing very accurately. If you understand what the benchmarks are doing, they can be very useful tools.

Some of the common and useful benchmarks include:

Bonnie

Bonnie has been around forever, and the numbers it produces are meaningful to many people. If nothing else, it's good tool for producing info to share with others. This is a pretty common utility for testing driver performance. It's only drawback is it sometimes requires the use of huge datasets on large memory machines to get useful results, but I suppose that goes with the territory.
Check Doug Ledford's list of benchmarks for more info on Bonnie. There is also a somwhat newer version of Bonnie called Bonnie++ that fixes a few bugs, and includes a couple of extra tests.


Dbench

My personal favorite disk io benchmarking utility is `dbench`. It is designed to simulate the disk io load of a system when running the NetBench benchmark suite. It seems to do an excellent job at making all the drive lights blink like mad. Always a good sign.
Dbench is available at The Samba ftp site and mirrors


http_load

A nice simple http benchmarking app, that does integrity checking, parallel requests, and simple statistics. Generates load based off a test file of urls to hit, so it is flexible.
http_load is available from ACME Labs


dkftpbench

A (the?) ftp benchmarking utility. Designed to simulate real world ftp usage (large number of clients, throttles connections to modem speeds, etc). Handy. Also includes the useful dklimits utility .
dkftpbench is available from Dan kegel's page


tiobench

A multithread disk io benchmarking utility. Seems to do an a good job at pounding on the disks. Comes with some useful scripts for generating reports and graphs.
The tiobench site.

dt
dt does a lot. disk io, process creation, async io, etc.

dt is available at The dt page


ttcp

A tcp/udp benchmarking app. Useful for getting an idea of max network bandwidth of a device. Tends to be more accurate than trying to guestimate with ftp or other protocols.

netperf
Netperf is a benchmark that can be used to measure the performance of many different types of networking. It provides tests for both unidirecitonal throughput, and end-to-end latency. The environments currently measureable by netperf include: TCP and UDP via BSD Sockets, DLPI, Unix Domain Sockets, Fore ATM API, HiPPI.
Info: http://www.netperf.org/netperf/NetperfPage.html
Download: ftp://ftp.sgi.com/sgi/src/netperf/

Info provided by Bill Hilf.

httperf
httperf is a popular web server benchmark tool for measuring web server performance. It provides a flexible facility for generating various HTTP workloads and for measuring server performance. The focus of httperf is not on implementing one particular benchmark but on providing a robust, high-performance tool that facilitates the construction of both micro- and macro-level benchmarks. The three distinguishing characteristics of httperf are its robustness, which includes the ability to generate and sustain server overload, support for the HTTP/1.1 protocol, and its extensibility to new workload generators and performance measurements.
Info: http://www.hpl.hp.com/personal/David_Mosberger/httperf.html
Download: ftp://ftp.hpl.hp.com/pub/httperf/

Info provided by Bill Hilf.

Autobench
Autobench is a simple Perl script for automating the process of benchmarking a web server (or for conducting a comparative test of two different web servers). The script is a wrapper around httperf. Autobench runs httperf a number of times against each host, increasing the number of requested connections per second on each iteration, and extracts the significant data from the httperf output, delivering a CSV or TSV format file which can be imported directly into a spreadsheet for analysis/graphing.
Info: http://www.xenoclast.org/autobench/
Download: http://www.xenoclast.org/autobench/downloads

Info provided by Bill Hilf.

General benchmark Sites

Doug Ledford's page
ResierFS benchmark page


System Monitoring
Standard, and not so standard system monitoring tools that can be useful when trying to tune a system.

vmstat

This util is part of the procps package, and can provide lots of useful info when diagnosing performance problems.
Heres a sample vmstat output on a lightly used desktop:

procs memory swap io system cpu
r b w swpd free buff cache si so bi bo in cs us sy id
1 0 0 5416 2200 1856 34612 0 1 2 1 140 194 2 1 97

And heres some sample output on a heavily used server:


procs memory swap io system cpu
r b w swpd free buff cache si so bi bo in cs us sy id
16 0 0 2360 264400 96672 9400 0 0 0 1 53 24 3 1 96
24 0 0 2360 257284 96672 9400 0 0 0 6 3063 17713 64 36 0
15 0 0 2360 250024 96672 9400 0 0 0 3 3039 16811 66 34 0

The interesting numbers here are the first one, this is the number of the process that are on the run queue. This value shows how many process are ready to be executed, but can not be ran at the moment because other process need to finish. For lightly loaded systems, this is almost never above 1-3, and numbers consistently higher than 10 indicate the machine is getting pounded.

Other interseting values include the "system" numbers for in and cs. The in value is the number of interupts per second a system is getting. A system doing a lot of network or disk I/o will have high values here, as interupts are generated everytime something is read or written to the disk or network.

The cs value is the number of context switches per second. A context switch is when the kernel has to take off of the executable code for a program out of memory, and switch in another. It's actually _way_ more complicated than that, but thats the basic idea. Lots of context swithes are bad, since it takes some fairly large number of cycles to performa a context swithch, so if you are doing lots of them, you are spending all your time chaining jobs and not actually doing any work. I think we can all understand that concept.


netstat


Since this document is primarily concerned with network servers, the `netstat` command can often be very useful. It can show status of all incoming and outgoing sockets, which can give very handy info about the status of a network server.
One of the more useful options is:


netstat -pa

The `-p` options tells it to try to determine what program has the socket open, which is often very useful info. For example, someone nmap's their system and wants to know what is using port 666 for example. Running netstat -pa will show you its satand running on that tcp port.

One of the most twisted, but useful invocations is:


netstat -a -n|grep -E "^(tcp)"| cut -c 68-|sort|uniq -c|sort -n

This will show you a sorted list of how many sockets are in each connection state. For example:


9 LISTEN
21 ESTABLISHED


ps

Okay, so everyone knows about ps. But I'll just highlight one of my favorite options:

ps -eo pid,%cpu,vsz,args,wchan

Shows every process, their pid, % of cpu, memory size, name, and what syscall they are currently executing. Nifty.


Utilities
Some simple utilities that come in handy when doing performance tuning.

dklimits

a simple util to check the acutally number of file descriptors available, ephemeral ports available, and poll()-able sockets. Handy. Be warned that it can take a while to run if there are a large number of fd's available, as it will try to open that many files, and then unlinkt them.
This is part of the dkftpbench package.


fd-limit


a tiny util for determining the number of file descriptors available.
fd-limit.c


thread-limit


A util for determining the number of pthreads a system can use. This and fd-count are both from the system tuning page for Volano chat, a multithread java based chat server.
thread-limit.c



System Tuning Links
http://www.kegel.com
Check out the "c10k problem" page in particular, but the entire site has _lots_ of useful tuning info.
http://linuxperf.nl.linux.org/

Site organized by Rik Van Riel and a few other folks. Probabaly the best linux specific system tuning page.
http://www.citi.umich.edu/projects/citi-netscape/

Linux Scalibity Project at Umich.
NFS Performance Tunging

Info on tuning linux kernel NFS in particular, and linux network and disk io in general
http://home.att.net/~jageorge/performance.html

Linux Performace Checklist. Some useful content.
http://www.linux.com/enhance/tuneup/

Miscelaneous performace tuning tips at linux.com
http://www.psc.edu/networking/perf_tune.html#Linux

Summary of tcp tuning info
2005/06/27 18:20 2005/06/27 18:20

Linux Kernel Tuning

FAQ 2005/06/27 18:20
How to set kernel tunables
The easiest method to set kernel parameters is by modifying the /proc filesystem (and hence the kernel directly) by using echo "value" > /proc/kernel/parameter. Then changes take effect immediately but must be reset at system boot up. Kernel tuning can be automated at boo time by putting the echo commands in /etc/rc.d/rc.local for Non-RedHat distributions or for RedHat derived distributions modify the /etc/sysctl.conf configuration file instead.

Increasing System Limits
Increasing the Maximum number of file handles and the inode cache
NOTE:
On all current versions of linux up to and including 2.2.10 and 2.3.9, inode caches DO NOT SHRINK like the file and dentry caches do when your applications need lots of ram.
This means if you set a really large inode cache, then you can lose a significant amount of RAM over time. On a server machine, this is expected, normal and desired. On a workstation machine, doing a kernel compile when your inode-max is set at a very large number will probably give far too much to the inode cache.
Empirical evidence suggests that 40960 entries in the inode cache will use up to 10 megabytes of ram. Your mileage may vary, and more data is necessary to confirm this number.
Linux 2.0.x - file-max defaults to 1024 so increase the value of /proc/sys/kernel/file-max to something reasonable like 256 for every 4M of RAM you have: i.e.. for a 64 M machine, set it to 4096.
The canonical command to change anything in the /proc hierarchy is (as root) echo "newvalue" >/proc/file/that/you/want/to/change, so for this item the command line is
echo "4096" >/proc/sys/kernel/file-max
Also increase /proc/sys/kernel/inode-max to a value roughly 3 to 4 times the number of open files. This is because the number of inodes open is at least one per open file, and often much larger than that for large files.
(the following was written by Tani Hosokawa)
Note: if you increase this beyond 1024, you may also have to edit include/linux/posix_types.h and increase this line:

#define __FD_SETSIZE 1024

That allows for a select to handle 1024 file descriptors. More than that, and stuff may break.

Linux 2.2.x/2.3.x - increase the value of /proc/sys/fs/file-max to something reasonable like 256 for every 4M of RAM you have: i.e.. for a 64 M machine, set it to 4096. As above, also increase the /proc/sys/fs/inode-max as well

Long Answer:
The above technique or modifying the constants in the kernel sources. Not usually the right answer because that will not survive a new kernel source tree. One of the best techniques is to add the above commands to /etc/rc.d/rc.local.

The exact number will vary from the above formula based on what you are actually doing with the machine. A file server or web server need a lot of open files, for instance, but a compute server does not.
Very large memory systems, especially 512 Megabytes or larger, probably should not have more than 50,000 open files and 150,000 open inodes. Of course if you are Mindcraft, this is a cheap and effective way to waste kernel memory.

Linux 2.4.x - ?

Here is another method of increasing these limits from www.linuxraid.org:

Aim: Increase the number of files that may be open simultaneously
Changes to include/linux/fs.h:
increase NR_FILE from 4096 to 65536
increase NR_RESERVED_FILES from 10 to 128
Changes to fs/inode.c:
increase MAX_INODE from 16384 to 262144
Note: MAX_INODE must be at least three times larger than NR_FILE.

Increasing the number of processes/tasks allowed
Linux 2.0.x - The default maximum is 512 tasks, half of which can be used by any single
user. Here's an excerpt from /usr/src/linux/include/linux/tasks.h
#define NR_TASKS 512 /* On x86 Max 4092, or 4090 w/APM configured. */

#define MAX_TASKS_PER_USER (NR_TASKS/2)
#define MIN_TASKS_LEFT_FOR_ROOT 4

Just change the 512 to something higher. You can change MAX_TASKS_PER_USER to
something else as well, although it's a nice precaution against simple process
table attacks. Properly managed systems shouldn't be vulnerable to that
though (you do set your MaxClients and whatnot, don't you?). Don't try to go
above the maximums. Your machine will just keep rebooting and rebooting.
(the preceding was written by Tani Hosokawa)

Linux 2.2.x/2.3.x -Edit /usr/src/linux/include/linux/tasks.h, modify the "NR_TASKS" value and then rebuild and install the kernel. (One person recommended changing NR_TASKS from 512 to 2048, and changing MIN_TASKS_LEFT_FOR_ROOT to 24.)

Linux 2.4.x - ?

Decrease the time before disposing of unused TCP keepalive requests (from linuxraid.org)
Changes to include/net/tcp.h:
decrease TCP_KEEPALIVE_TIME from 2 hours to 5 minutes
Download: http://www.linuxraid.org/tcp-keepalive.patch
Increase the number of TCP/UDP ports that may be used simultaneously (from linuxraid.org)
On 2.2 and 2.4 kernels, the local port range can be changed via sysctl
echo 1024 25000 > /proc/sys/net/ipv4/ip_local_port_range
Allows more local ports to be available. Generally not a issue, but in a benchmarking scenario you often need more ports available. A common example is clients running `ab` or `http_load` or similar software.
Increasing the amount of memory associated with socket buffers
Increasing the amount of memory associated with socket buffers can often improve performance. Things like NFS in particular, or apache setups with large buffer configured can benefit from this.
echo 262143 > /proc/sys/net/core/rmem_max
echo 262143 > /proc/sys/net/core/rmem_default
This will increase the amount of memory available for socket input queues. The "wmem_*" values do the same for output queues.
Note: With 2.4.x kernels, these values are supposed to "autotune" fairly well, and some people suggest just instead changing the values in:

/proc/sys/net/ipv4/tcp_rmem
/proc/sys/net/ipv4/tcp_wmem
Increasing the amount of memory associated with socket buffers
Increasing the amount of memory associated with socket buffers can often improve performance. Things like NFS in particular, or apache setups with large buffer configured can benefit from this.
echo 262143 > /proc/sys/net/core/rmem_max
echo 262143 > /proc/sys/net/core/rmem_default
This will increase the amount of memory available for socket input queues. The "wmem_*" values do the same for output queues.
Note: With 2.4.x kernels, these values are supposed to "autotune" fairly well, and some people suggest just instead changing the values in:

/proc/sys/net/ipv4/tcp_rmem
/proc/sys/net/ipv4/tcp_wmem
There are three values here, "min default max".
Turning off tcp_sack and tcp_timestamps
These reduce the amount of work the TCP stack has to do:
echo 0 > /proc/sys/net/ipv4/tcp_sack
echo 0 > /proc/sys/net/ipv4/tcp_timestamps
This disables "RFC2018 TCP Selective Acknowledgements", and "RFC1323 TCP timestamps"
Increasing shared memory and ipc limits
Some applications, databases in particular, sometimes need large amounts of SHM segments and semaphores. The default limit for the number of shm segments is 128 for 2.2.
This limit is set in a couple of places in the kernel, and requires a modification of the kernel source and a recompile to increase them.

A sample diff to bump them up:

--- linux/include/linux/sem.h.save Wed Apr 12 20:28:37 2000
+++ linux/include/linux/sem.h Wed Apr 12 20:29:03 2000
@@ -60,7 +60,7 @@
int semaem;
};

-#define SEMMNI 128 /* ? max # of semaphore identifiers */
+#define SEMMNI 512 /* ? max # of semaphore identifiers */
#define SEMMSL 250 /* <= 512 max num of semaphores per id */
#define SEMMNS (SEMMNI*SEMMSL) /* ? max # of semaphores in system */
#define SEMOPM 32 /* ~ 100 max num of ops per semop call */
--- linux/include/asm-i386/shmparam.h.save Wed Apr 12 20:18:34 2000
+++ linux/include/asm-i386/shmparam.h Wed Apr 12 20:28:11 2000
@@ -21,7 +21,7 @@
* Keep _SHM_ID_BITS as low as possible since SHMMNI depends on it and
* there is a static array of size SHMMNI.
*/
-#define _SHM_ID_BITS 7
+#define _SHM_ID_BITS 10
#define SHM_ID_MASK ((1<<_SHM_ID_BITS)-1)

#define SHM_IDX_SHIFT (_SHM_ID_BITS)


Theoretically, the _SHM_ID_BITS can go as high as 11. The rule is that _SHM_ID_BITS + _SHM_IDX_BITS must be <= 24 on x86.
In addition to the number of shared memory segments, you can control the maximum amount of memory allocated to shm at run time via the /proc interface. /proc/sys/kernel/shmmax indicates the current. Echo a new value to it to increase it.

echo "67108864" > /proc/sys/kernel/shmmax
To double the default value.
A good resource on this is Tunings The Linux Kernel's Memory. Linux Maximus: How to Get Maximum Performance from Linux and Oracle also includes some useful about tuning shm for oracle, amongst other things.

The best way to see what the current values are, is to issue the command:

ipcs -l
Ptys and ttys
The number of ptys and ttys on a box can sometimes be a limiting factor for things like login servers and database servers.
On Red Hat Linux 7.x, the default limit on ptys is set to 2048 for i686 and athlon kernels. Standard i386 and similar kernels default to 256 ptys.

The config directive CONFIG_UNIX98_PTY_COUNT defaults to 256, but can be set as high as 2048. For 2048 ptys to be supported, the value of UNIX98_PTY_MAJOR_COUNT needs to be set to 8 in include/linux/major.h

With the current device number scheme and allocations, the maximum number of ptys is 2048.

Increasing Thread Limits
Limitations on threads are tightly tied to both file descriptor limits, and process limits.
Under Linux, threads are counted as processes, so any limits to the number of processes also applies to threads. In a heavily threaded app like a threaded TCP engine, or a java server, you can quickly run out of threads.

The first step to increasing the possible number of threads is to make sure you have boosted any process limits as mentioned before.

There are few things that can limit the number of threads, including process limits, memory limits, mutex/semaphore/shm/ipc limits, and compiled in thread limits. For most cases, the process limit is the first one to run into, then the compiled in thread limits, then the memory limits.

To increase the limits, you have to recompile glibc. Oh fun!. And the patch is essentially two lines!. Woohoo!


--- ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h.akl Mon Sep 4
19:37:42 2000
+++ ./linuxthreads/sysdeps/unix/sysv/linux/bits/local_lim.h Mon Sep 4
19:37:56 2000
@@ -64,7 +64,7 @@
/* The number of threads per process. */
#define _POSIX_THREAD_THREADS_MAX 64
/* This is the value this implementation supports. */
-#define PTHREAD_THREADS_MAX 1024
+#define PTHREAD_THREADS_MAX 8192

/* Maximum amount by which a process can descrease its asynchronous I/O
priority level. */
--- ./linuxthreads/internals.h.akl Mon Sep 4 19:36:58 2000
+++ ./linuxthreads/internals.h Mon Sep 4 19:37:23 2000
@@ -330,7 +330,7 @@
THREAD_SELF implementation is used, this must be a power of two and
a multiple of PAGE_SIZE. */
#ifndef STACK_SIZE
-#define STACK_SIZE (2 * 1024 * 1024)
+#define STACK_SIZE (64 * PAGE_SIZE)
#endif

/* The initial size of the thread stack. Must be a multiple of PAGE_SIZE.
* */
Now just patch glibc, rebuild, and install it. ;-> If you have a package based system, I seriously suggest making a new package and using it.
Two references on how to do this are Jlinux.org, and Volano.Both describe how to increase the number of threads so Java apps can use them.

Increasing ulimits or shell limits
OK, so this isn't kernel tuning but it may be as issue that you have to deal with, here is how you set the shell security limits up for you application:
"In bash and similar shells you can use these three
commands:
ulimit -a
ulimit -Ha
ulimit -s unlimited
that will respectively print soft limits, hard limits
and remove the stack limit."

The source for this information came from this Usenet article.

Large File Support
Large file support - support for files greater than 2 GB - is a kernel AND user space issue, meaning that not just the kernel has to be able to support file larger than 2 GB but also the C library (libc or for GUN/Linux glibc) and all file accessing utilities have to support it as well. See the LFS section in the links page for links with detailed information.


Improving System Performance

Tuning (delaying) filesystem cache synchronization (flushing)
Increasing the time between when the kernel writes will minimize the amount of I/O done at the cost of losing more data if the system were to crash. See the following link from the linuxdoc.org site from the Securing and Optimizing Red Hat Linux Edition.

Tuning virtual memory system to use less memory on servers with *lots* of memory on 2.0.x or 2.2.x (from Tani Hosokawa)
Memory shortages (even though you've got tons) - for Linux 2.0.x/2.2.x
Sometimes, you'll end up with a situation where the kernel can't seem to find
enough memory to load a program for you, even though you've got tons of
memory. This may be caused by the filesystem buffers using up the extra, and
not having enough memory immediately available. You can often fix this by
modifying the contents of /proc/sys/vm/freepages (the three values are
min_free_pages, free_pages_low, and free_pages_high in case you care -- check
the source for more details). "256 512 768" is common, but often not enough.
I use "1024 2048 3072" usually. That's almost definitely enough memory to load
anything, and with 384 megs of RAM, it's not going to hurt performance by
reducing the amount available for caching.
2005/06/27 18:20 2005/06/27 18:20
컴퓨터의 시간들은 제각기 다르죠.

그렇다고 다시 시간을 설정을 해도 어느정도 시간이 흐른후에는

시간이 약간씩은 틀려지기 마련입니다.

이것을 관리자가 일일히 체크해서 맞추기도 귀찮구요.

이제는 일일이 시간을 맞출필요가 없습니다. 리눅스에서는 다른 서버에서

시간을 가져와 설정을 할수가 있죠. 아래와 같이 하시면 됩니다.

/etc/crontab <- 이 파일을 연후

0 0 * * 1 root rdate -s time.bora.net && clock -w <- 를 한줄 삽입하세요.

위에서 time.bora.net 는 시간을 가져올 서버입니다.

콘솔에서도 할수가 있습니다. 콘솔에서의 방법은

rdate -s time.bora.net && clock -w <-- 이렇게 하시고 엔터를 꽝 치시면 되죠!



[root@inet /etc]# date
Thu Nov 23 18:45:30 KST 2000
[root@inet /etc]# rdate -s time.bora.net && clock -w
[root@inet /etc]# date
Thu Sep 23 18:45:16 KST 2003
2005/06/27 18:19 2005/06/27 18:19
시스템을 관리하다보면 보안이나 서버부하등 여러 가지 사유로 인하여 ping에 응답하지 못하게 설정할 필요를 느낄 때가 있습니다.

이때에는 다음과 같이 설정함으로서 ping에 응답하지 못하게 하거나 다시 응답하게할 수 있습니다.

첫째, ping에 응답하지 못하게 하려면 다음과 같이 /proc/sys/net/ipv4/icmp_echo_ignore_all 파일값을 1로 설정합니다.
ex) /proc/sys/net/ipv4/echo 1 > icmp_echo_ignore_all

둘째, 다시 ping에 응답하게 하려면 다음과 같이 /proc/sys/net/ipv4/icmp_echo_ignore_all 파일값을 0으로 설정합니다.
ex) /proc/sys/net/ipv4/echo 0 > icmp_echo_ignore_all
2005/06/27 18:18 2005/06/27 18:18

로그 파일 관리하기

FAQ 2005/06/27 18:17
시스템 관리자들은 정기적으로 로그 파일을 체크하고 관리해야 합니다.
리눅스에는 보안과 시스템 등에 관련된 다양한 로그 파일들이 존재하며
주로 /var/log 디렉토리에 싸이게 됩니다.

- dmesg
Linux가 시작될 때 나타나는 메시지들을 기록한 파일로 터미널에서
dmesg 명령을 입력하면 보여지는 내용과 동일합니다. 주로 시스템의
구동과 종료시에 문제점이 발생하는 경우 그 원인을 체크해 볼 수
있는 중요한 파일입니다.

- messages
다양한 서버의 데몬이나 xinetd와 관련된 서비스를 사용할 때 기록
되는 로그파일로 데몬에 문제가 발생할 경우 체크합니다.

- secure
시스템에 로그인하거나 인증을 요하는 작업을 한 경우 기록되는 파일
로 보안상 매우 중요한 로그입니다.

- lastlog
각 사용자가 마지막으로 로그인한 날짜를 기록하고 있습니다.
lastlog 명령어를 사용하여 확인할 수 있습니다.

- wtmp
시스템에 접속한 모든 사용자의 로그를 기록하는 파일로 las, 명령어
로 확인 할 수 있습니다.

- xferlog
FTP 서비스의 엑세스를 기록하는 로그입니다.

로그 파일의 관리에 소홀하면, 로그 파일이 계속 커져 시스템 FULL 과
같은 장애가 발생하고 디스크에도 심각한 문제를 일으킬 수 있으므로
logrotate와 같은 프로그램으로 자동으로 로그파일을 순환시켜야 합니다.
2005/06/27 18:17 2005/06/27 18:17
Introduction

The purpose of this document is to strengthen the UNIX IP stack against
a variety
of attack types prevalent on the Internet today. This document details
the
settings recommended for UNIX servers designed to provide network
intensive
services such as HTTP or routing (firewall services). This document
covers
the following UNIX variants:


A. IBM AIX 4.3.X
B. Sun Solaris 7
C. Compaq Tru64 UNIX 5.X
D. HP HP-UX 11.0 (research ongoing)
E. Linux kernel 2.2 (tested both SuSE Linux 7.0 and RedHat
7.0)
F. FreeBSD
G. IRIX 6.5.10


Windows NT/2000 will be covered in future releases.

The tuning changes noted below will not remain across reboots.
Thus, these changes should be added to a runtime commands file so
that the changes are enacted at each boot.

AIX - /etc/rc.net
Solaris - /etc/init.d/inetinit
Tru64 UNIX - Use the sysconfigdb or
dxkerneltuner command
HP-UX - /etc/rc.config.d/nddconf
Linux kernel 2.2 - /etc/sysctl.conf
FreeBSD - /etc/rc.conf
IRIX - Use the systune command


No tuning steps should be undertaken without a keen insight into
the purpose and effect of such steps. It is assumed that the
personnel who undertake such tuning are well versed in the UNIX
kernel with bit-level understanding of TCP/IP and the RFCs that
govern IP behavior.



Revision History

Version 1.0 - Created the AIX IP stack tuning guide
Version 2.0 - Added Solaris and additional AIX tuning tips, reformated
doc
Version 2.2 - Added ARP tuning tips
Version 2.3 - Added Compaq Tru64 UNIX SYN defense tips
Version 2.4 - Added HP HP-UX 11.0 tuning tips
Version 2.5 - Added Linux and FreeBSD tuning tips
Version 2.6 - Added IRIX 6.5.10 and additional FreeBSD tuning tips
Version 2.7 - Added additional HP-UX 11.0 tuning tips



Credits
This has become a global effort, and this document is made more rich and
valuable thanks to the input of several very helpful folks! Kudos and
lauds for the folks below:

Thanks to the Compaq Software Security Response Team for the Tru64 UNIX
SYN flood defense pointers.

For HP-UX 11.0, thanks to Tom Harrold for running ndd over and over at my
every request. :-)

Thanks to Klaus Moeller for a copious collection of Linux tuning tips.

Thanks to Andrew Korty for the FreeBSD tuning tips.

Thanks to Christian Lambert and Alex Icasiano of SGI for the IRIX tuning
tips.

Thanks, as always, to the FIRST
community for support, questions, and feedback.


General IP Stack Tuning Recommendations

1. TCP send and receive spaces

The TCP send and receive spaces directly effect the TCP window
size parameter. An increased window size will allow for more
efficient transfers, particularly bulk transfers such as FTP
and HTTP. The default for each is not optimal, and should be
increased to 32768 bytes. This value should not be increased
above 64K bytes unless the implications of
RFC1323
and RFC2018
are fully understood and support for both is enabled.

Do not enable RFC1323 without also enabling support for RFC2018.
Remember, pipe drain is a Bad Thing[tm].

A. AIX
/usr/sbin/no -o tcp_sendspace=32768
/usr/sbin/no -o tcp_recvspace=32768


B. Solaris
/usr/sbin/ndd -set /dev/tcp tcp_xmit_hiwat 32768
/usr/sbin/ndd -set /dev/tcp tcp_recv_hiwat 32768


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
The TCP send and receive spaces are set to 32768 by default


E. Linux kernel 2.2
While Linux automagically assigns the TCP send and receive
spaces,
support for both RFC1323 (large window support,
net.ipv4.tcp_window_scaling) and RFC2018 (SACK
support,
net.ipv4.tcp_sack) are enabled by default.


F. FreeBSD
sysctl -w net.inet.tcp.sendspace=32768
sysctl -w net.inet.tcp.recvspace=32768


G. IRIX
The default settings for IRIX are 64Kbytes for both the
TCP send
and receive spaces.




2. Socket queue defense against SYN attacks

While great effort is undertaken to defend any network from those
with malicious intent, several ports (largely TCP) must remain
open to conduct business. Internet vandals may attempt to
exploit these ports to launch a denial of service attack. One of
the most popular attacks remains the SYN flood, wherein the socket
queue of the attacked host is overwhelmed with bogus connection
requests. To defend against such attacks, certain UNIX variants
maintain separate queues for inbound socket connection requests.
One queue is for half-open sockets (SYN received, SYN|ACK sent),
the other queue for fully-open sockets awaiting an accept()
call from the application. These two queues should be increased so
that an attack of low to moderate intensity will have little to no
effect on the stability or availability of the server.

A. AIX
/usr/sbin/no -o clean_partial_conns=1
This setting will instruct the kernel to randomly remove
half-open sockets from the q0 queue to make room for
new
sockets.


B. Solaris
/usr/sbin/ndd -set /dev/tcp tcp_conn_req_max_q 1024
The q queue holds sockets awaiting an accept()

call from the application.


/usr/sbin/ndd -set /dev/tcp tcp_conn_req_max_q0 2048
The q0 queue contains half-open sockets.


C. Tru64 UNIX
/sbin/sysconfig -r socket sominconn=65535
The value of sominconn determines how many simultaneous
incoming
SYN packets can be handled by the system.


/sbin/sysconfig -r socket somaxconn=65535
The value of somaxconn sets the maximum number of pending
TCP
connections.


D. HP-UX
/usr/sbin/ndd -set tcp_syn_rcvd_max 1024
/usr/sbin/ndd -set tcp_conn_request_max 200


E. Linux kernel 2.2
/sbin/sysctl -w net.ipv4.tcp_max_syn_backlog=1280
Increases the size of the socket queue (effectively, q0).


/sbin/sysctl -w net.ipv4.tcp_syn_cookies=1
Enables support for TCP SYN cookies, which mitigates the
effectiveness
of SYN floods. However, this may cause performance
problems for
large windows (see RFC1323 and RFC2018). To read
more about SYN
cookies, please review DJ Bernstein's paper
here.


F. FreeBSD
sysctl -w kern.ipc.somaxconn=1024


G. IRIX
The listen() queue is hardcoded to 32. However,
the system
actually enforces the limit of pending connections as
((3 * backlog) / 2) + 1. This yields a maximum
backlog of 49
connections.




3. Redirects

A miscreant can use IP redirects to modify the routing table on a
remote host. In a well-designed network, redirects to the end
stations should not be required. Both the sending and accepting
of redirects should be disabled.

A. AIX
/usr/sbin/no -o ipignoreredirects=1
/usr/sbin/no -o ipsendredirects=0


B. Solaris
/usr/sbin/ndd -set /dev/ip ip_ignore_redirect 1
/usr/sbin/ndd -set /dev/ip ip_send_redirects 0


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
/usr/sbin/ndd -set /dev/ip ip_send_redirects 0


E. Linux kernel 2.2
/sbin/sysctl -w net.ipv4.conf.all.send_redirects=0
/sbin/sysctl -w net.ipv4.conf.all.accept_redirects=0


F. FreeBSD
sysctl -w net.inet.icmp.drop_redirect=1
sysctl -w net.inet.icmp.log_redirect=1
sysctl -w net.inet.ip.redirect=0
sysctl -w net.inet6.ip6.redirect=0


G. IRIX
/usr/sbin/systune icmp_dropredirects to 1




4. ARP cleanup

It is possible for a miscreant to create a resource exhaustion or
performance degredation by filling the IP route cache with bogus
ARP entries. In Solaris, there are two parameters that govern the
cleanup interval for the IP route cache. For unsolicited ARP
responses, the parameter to be tuned is arp_cleanup_interval. In
AIX, the cleanup interval is governed by the value of arpt_killc.
However, this parameter governs both solicited and unsolicited ARP
entries. For this reason, it is likely best to leave the parameter
at the default setting of 20 minutes.

A. AIX
/usr/sbin/no -o arpt_killc=20


B. Solaris
/usr/sbin/ndd -set /dev/arp arp_cleanup_interval
60000


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
By default set to five minutes.


E. Linux kernel 2.2
No tuning recommendations.


F. FreeBSD
sysctl -w net.link.ether.inet.max_age=1200


G. IRIX
No tuning recommendations.




5. Source routing

With source routing, an attacker can attempt to reach internal IP
addresses - including RFC1918 addresses. It is important to disable
the acceptance of source routed packets to prevent subtle probes of
your internal networks.

A. AIX
/usr/sbin/no -o ipsrcroutesend=0
Disable the sending of source routed packets.


/usr/sbin/no -o ipsrcrouteforward=0
This is important if the box is routing, e.g. a firewall.
Disable this feature to prevent the host from
forwarding source
routed packets.


B. Solaris
/usr/sbin/ndd -set /dev/ip ip_src_route_forward 0
This is important if the box is routing, e.g. a firewall.
Disable this feature to prevent the host from
forwarding source
routed packets.


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
ndd -set /dev/ip ip_forward_src_routed 0
Disable this feature to prevent the host from forwarding
source
routed packets.


E. Linux kernel 2.2
/sbin/sysctl -w
net.ipv4.conf.all.accept_source_route=0
Drop all source route packets.


/sbin/sysctl -w net.ipv4.conf.all.forwarding=0
/sbin/sysctl -w net.ipv4.conf.all.mc_forwarding=0
Do not forward source routed frames.


F. FreeBSD
sysctl -w net.inet.ip.sourceroute=0
sysctl -w net.inet.ip.accept_sourceroute=0


G. IRIX
/usr/sbin/systune ipforward to 2




6. TIME_WAIT setting

On a busy web server, many sockets may linger in the TIME_WAIT state.
This is caused by improperly coded client applications that do not
properly shut down a socket. This can also be used as a type of DDoS
attack.

A. AIX
No tuning recommendations.


B. Solaris
/usr/sbin/ndd -set /dev/tcp tcp_time_wait_interval
60000
This parameter effects the amount of time a TCP socket will
remain in the TIME_WAIT state. The default is quite
high
for a busy web server, so it should be lowered to
60000
milliseconds (60 seconds). The parameter name was
corrected
in Solaris 7 and higher. Prior to Solaris 7, the
parameter
was incorrectly labeled as tcp_close_wait_interval.


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
ndd -set /dev/tcp tcp_time_wait_interval 60000
Sockets will linger in TIME_WAIT state no more than 60
seconds.


E. Linux kernel 2.2
/sbin/sysctl -w net.ipv4.vs.timeout_timewait=60
Sockets will linger in TIME_WAIT state for no more than 60
seconds.


F. FreeBSD
No tuning recommendations.


G. IRIX
/usr/sbin/systune tcp_2msl to 60




7. Broadcast ECHO response

Smurf attacks work by sending ICMP 8 0 (ECHO REQUEST) messages to a
broadcast address from a spoofed address. Some IP stacks will respond,
by default, to such messages. This should be disabled. Further, if the
host is a firewall (router), it should not propogate directed broadcasts.

A. AIX
/usr/sbin/no -o directed_broadcast=0
Do not respond to directed broadcasts.


B. Solaris
/usr/sbin/ndd -set /dev/ip ip_respond_to_echo_broadcast
0
Do not respond to directed broadcasts.


/usr/sbin/ndd -set /dev/ip
ip_forward_directed_broadcasts 0
Do not forward directed broadcasts.


C. Tru64 UNIX
No tuning recommendations.


D. HP-UX
ndd -set /dev/ip ip_respond_to_echo_broadcast 0
Do not respond to directed broadcasts.


ndd -set /dev/ip ip_forward_directed_broadcasts 0
Do not forward directed broadcasts.


E. Linux kernel 2.2
/sbin/sysctl -w
net.ipv4.icmp_echo_ignore_broadcasts=1
Do not respond to directed broadcasts.


F. FreeBSD
sysctl -w net.inet.icmp.bmcastecho=0


G. IRIX
/usr/sbin/systune allow_brdaddr_srcaddr to 0




8. Other broadcast probes

There are two other broadcast probes that a miscreant could utilize
against a network. The address mask query can be used to map out the
size of the netblock, and set a range for further probes. The
timestamp broadcast is another means of mapping and fingerprinting
hosts.

A. AIX
/usr/sbin/no -o icmpaddressmask=0
Prevent address mask queries.


B. Solaris
/usr/sbin/ndd -set /dev/ip
ip_respond_to_address_mask_broadcast 0
Prevent address mask queries.


/usr/sbin/ndd -set /dev/ip
ip_respond_to_timestamp_broadcast 0
Disable timestamp broadcast query response.


C. Tru64 UNIX
No tuning recomendations.


D. HP-UX
ndd -set /dev/ip ip_respond_to_address_mask_broadcast
0
Prevent the host from revealing the configured netmask.


ndd -set /dev/ip ip_respond_to_timestamp_broadcast 0
Disable timestamp broadcast query response.


E. Linux kernel 2.2
No tuning recommendations.


F. FreeBSD
sysctl -w net.inet.icmp.maskrepl=0


G. IRIX
Use ipfilterd to block unwanted ICMP types.




9. Support for RFC1948

This will utilize RFC1948
sequence number generation techniques to ensure that the sequence
number for a given TCP socket is very difficult to guess. This
tactic prevents TCP session hijacking, which could be quite an issue
with e-commerce.

B. Solaris
Set TCP_STRONG_ISS=2 in /etc/default/inetinit.
This will require a reboot to take effect.


G. IRIX
/usr/sbin/systune tcpiss_md5 to 1
2005/06/27 18:17 2005/06/27 18:17

유용한 vi명령어

FAQ 2005/06/27 18:16
o 삽입
I: 줄의 제일 앞에서 입력
A: 줄의 제일 끝에서 입력

o 콤보command
4w: 4단어 skip후 이동
4b: 4단어 skip후 이동
4j,h,k,l: 커서이동시 지정한 수만큼 건너뛰므로
이동을 좀 더 빨리 할 수 있다.

o 줄의 결합(J)
2줄이 있고, 2째줄을 1째줄 끝에 붙이고 싶다면,
1째줄에서 J를 입력하면 된다.

o 커서이동
0: 줄의 처음
^: 줄의 처음(글자가 시작되는 처음)
$: 줄의 끝
w: 단어단위 이동
e: w와 같으나 단어의 끝으로 이동
b: w의 반대방향으로 이동
H, M, L: 커서를 화면 상,중,하로 이동

o 검색(/후 검색할 단어입력)
n: 뒤로 검색
N: 앞으로 검색

o 매크로
ab aa aaaa: aa를 입력하면 aaaa로 자동변환

o 치환
s/pattern/replace: 현재줄의 첫번째 matching pattern치환
s/pattern/replace/g: 현재줄의 모든 matching pattern치환
%s/pattern/replace/g: 모든 줄의 치환
line,lines/pattern/replace: 해당 범위의 치환

o 저장
w>> file: 지정한 파일에 추가

o 윈도 split
vi내에서 위아래로 윈도가 분활되면서 2개의 파일을
동시에 open/편집할 수 있다.
ex-mode(:프롬프트상태)에서 'sp 파일이름'
윈도우가 전환은 Ctrl+ww

o 기타
1. d의 경우 command모드로 계속 남아 있으나 c는 삭제후
insert모드로 변환한다. cc, c$, cw등은 유용하게 사용될 수 있다.
2. .은 마지막 명령을 되풀이한다.

o visual모드
윈도의 텍스트 에디터와 같이 선택부분이 반전되면서 복사,
삭제 등을 할 수 있다.
v로 visual모드로 집입하여 커서키를 사용해 원하는 부분을 선택한다.
복사는 y, 삭제/잘라내기는 d로 할 수 있다.

o vi 설정(vim 설정)
자신의 홈디렉토리에 .vimrc를 생성하고 다음과 같이 할 수 있다.

set ai : auto-indent
set ts=4 : tab stop
set nu : numbering

o 윈도에서 작업중 vi에 붙여넣기시 계단현상발생 방지
:set paste

o 위치기억(UltraEdit의 ALT-F2, F2와 동일한 기능)
m{a-z}: 현재위치를 {a-z}로 북마크함
`{a-z}: 기억해둔 {a-z}로 이동. 보통 한개만 등록했다면
그냥 ``를 사용하면 된다.

o 레코딩
설정파일의 주석추가/삭제시 유용하게 사용할 수 있다.
(이미 vi에 매크로기능이 있지만, 레코딩이 UltraEdit의 매크로기능과 유사하다.)
q{a-z}: {a-z}로 레코딩 시작. {a-z}만 가능한게 아니고 실제 {0-9a-zA-Z"}를
적기 번거로워 이렇게 표시만 한 것이다.
q: 레코딩 종료
@{a-z}: 레코딩 내용 적용(@@를 하면 바로 이전의 레코딩내용을 적용, N@@은
N으로 지정한 숫자만큼 적용)

----------------------
[vi] 치환(substitute)
----------------------
[범위] s [/패턴/대치/] [옵션] [카운트]

- 옵션
c 치환전 확인 유무 물음
g 글로벌 치환
p 치환된 마지막 라인 출력

- 예제
:1,10s/yes/no/g 처음 10행 치환
:%s/[Hh]ello/Hi/gc 치환 확인 물음
:s/Fortran/\U&/ 3 다음 3행의 "Fortran"을 대문자로 치환
:g/^[0-9][0-9]*/s//Line &:/ 숫자가 있는 모든라인에 Line: 추가

----------------------
[vi] 파일 오가며 편집하기
----------------------
:e#

"f4yy → :w → :e other_file → "fp
:f 버퍼에 4라인 복사후 붙이기
"F6yy
:f 버퍼에 6라인 추가
2005/06/27 18:16 2005/06/27 18:16
복잡한 명령어와 옵션을 간단히 입력할 수 있는 문자열로 치환한다.

사용법 : alias name[=value] 

옵션을 포함한 긴 명령어를 사용할 때 마다 매번 입력하지 않고 간단한 문자열로 치환 하여 사용하기 위해 alias가 이용된다. 터미널에서 rm 명령어를 이용하여 파일을 삭제할 때 파일을 지울 것인지 다시 한번 묻는 옵션을 사용하지 않아도 기본 rm 명령어가 이 옵션을 사용하고있거나 ls 명령어를 이용해 파일 목록을 보았을 때 색으로 구분되는 것은 대부분의 환경에서 미리 alias로 해당 옵션을 예약 해 놓았기 때문이다.
셸은 내부 명령 alias 와 unalias를 이용하여 이런 예약 내용을 목록에 설정하고 해제 한다. 어떠한 명령어가 입력되면 이 명령어의 앞에서부터 문자열과 일치하는 alias가 있는지 목록에서 확인하고, 일치하면 원래의 명령어로 치환하여 실행한다.
셸 프롬프트에서 alias를 입력해 보자. 현재 시스템에 정의된 alias의 목록을 볼 수 있다. 이전에 alias 관련 명령을 실행해 본 적이 없다면, 이것은 설치할 때부터 기본 설정된 내용일 것이다.

# alias 
alias cp='cp -i' 
alias l.='ls -d .[a-zA-Z]* --color=tty' 
alias ll='ls -l --color=tty' 
alias ls='ls --color=tty' 
alias mv='mv -i' 
alias rm='rm -i' 
alias vi='vim' 

원래 cp명령은 복사 받을 파일이 이미 존재하는지 신경쓰지 않고 복사 하지만, cp 명령에 i 옵션을 붙이게 되면, 같은 이름의 파일이 있을 때 덮어씌울 것인지 여부를 물어본다. 이런 옵션이 있으면 실수로 덮어씌우는 일을 줄일 수 있으므로 미리 cp명령에 i 옵션까지 주어서 cp alias를 지정하였다. 이와 같은 명령은 대개 기본으로 설정된 내 용이다.
그러면 cp alias를 해제해 보자. alias 해제 명령은 unalias이다.

#unalias cp 

alias명령으로 예약된 내용을 보자.

#alias 
alias l.='ls -d .[a-zA-Z]* --color=tty' 
alias ll='ls -l --color=tty' 
alias ls='ls --color=tty' 
alias mv='mv -i' 
alias rm='rm -i' 
alias vi='vim'

위의 cp alias가 없어졌다.
그럼, 다시 cp alias를 생성한다.

#alias cp='cp -i' 

다시 alias명령으로 확인하면 생성된 cp alias를 볼 수 있다. 위와 같은 방법으로 자주 쓰는 명령어와 옵션을 간단하게 줄여 사용할 수 있다. 예를들어 많이 사용하는 tar 명령과 옵션을 다음과 같이 만들어 놓으면 편리하다.

#alias tarx='tar xvpf' 
#alias tarc='tar cvff' 
#alias tarz='tar xvpfz' 

다른 명령어도 같은 방식으로 응용해 보자. 또한, alias를 설정한 상태로 원래의 명령어를 사용하기 위해 다음과 같은 방법을 사용할 수 있다.

#\cp 

혹은

#/bin/cp 

명령어 앞에\(백슬래시)가 붙어 있으면 alias를 무시하고 원래의 명령을 실행하라는뜻이다. 또한 절대 경로를 입력하여 명령어를 실행할 경우에는 alias를 사용할 수 없다.

[관련명령어]
unalias alias를 해제한다.
2005/06/27 18:10 2005/06/27 18:10