Skip to content

서버설정

OS 기본 설정

CentOS1과 Ubuntu2 환경에서 기본적으로 수행해야 하는 설정이다.

SUDO 설정

다음 명령어로 sudo 설정을 편집한다.

visudo

sudoers 설정은 아래와 같은 코드를 포함하거나 수정되어야 한다.

# Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
nuri    ALL=(ALL)       ALL
... 중략 ...

# Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL
# %nuri   ALL=(ALL)       ALL

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

설정 편집을 완료한 후 그룹에 사용자를 추가한다.

# wheel 그룹에 추가
usermod -aG wheel nuri

sudo 사용

  • root 권한
sudo su -

앞으로 별다른 지시가 없는한 root 권한으로 작업하는 것으로 한다.

업데이트 자동화

  • yum-cron : CentOS7의 경우 이 패키지를 통해 자동화
yum -y update
yum -y install epel-release
yum -y install yum-cron
vi /etc/yum/yum-cron.conf
# apply_updates = yes 로 수정

systemctl enable --now yum-cron.service
apt-get install cron-apt

vi  /etc/cron.d/cron-apt
# 0 4  * * * root test -x /usr/sbin/cron-apt && /usr-sbin/cron-apt

ln -s /usr/sbin/cron-apt /etc/cron.weekly/

NTP 설정

NTP 서비스 시작

systemctl start ntpd
cat /etc/ntp.conf
service ntp start
cat /etc/ntp.conf

Statum 설정

server kr.pool.ntp.org iburst
server time.bora.net iburst
server time.kriss.re.kr iburst
  • iburst 옵션을 추가해두면 기동 할 때 8회 싱크 시도 > 결과적으로 보다 빠르게 싱크
# 수동 시간 설정
ntpdate kr.pool.ntp.org

# 차이보기
ntpdate -d kr.pool.ntp.org

ntpq -p

timedatectl set-ntp yes

timedatectl set-timezone Asia/Seoul

date
yum -y install ntp
apt install ntp

명령어 권한 제한

  • 보안에 문제가 될 수 있는 명령어는 root계정 또는 wheel그룹에게만 권한을 부여
# 컴파일러 퍼미션 변경
chmod 100 /usr/bin/gcc /usr/bin/g++
chattr +i /usr/bin/gcc /usr/bin/g++
# su명령은 wheel그룹만 가능
chown root.wheel /bin/su
chmod 4750 /bin/su
chattr +i /bin/su
# 기타 명령 퍼미션 변경
chmod 750 /usr/sbin/useradd
chmod 750 /usr/bin/top
chmod 750 /sbin/fdisk
chmod 750 /sbin/mkfs*
chmod 750 /sbin/fsck*

보안 설정

Fail2ban 설정

  • 인증 실패시 접속을 차단
  • 내부 서버에서 접속은 차단 제외

Fail2ban 설치

yum -y install fail2ban
apt-get install fail2ban

Fail2ban 구성

    cat >>/etc/fail2ban/jail.d/sshd.conf  << EOF
    [DEFAULT]
    ## 차단하지 않을 IP
    ignoreip=127.0.0.1/8 10.0.0.0/8

    # 접속을 차단할 시간. 1일
    bantime  = 86400

    # 최대 허용 횟수
    maxretry = 10

    #아래 시간동안 maxretry횟수만큼 실패시 차단
    findtime  = 86400

    # CentOS 는 00-firewalld.conf가 있음.
    # banaction = firewallcmd-ipset

    [sshd]
    enabled=true
    port = 2222
    filter = sshd

    EOF

Fail2ban 기동

systemctl enable --now fail2ban
service fail2ban restart

fail2ban 활용

# 차단된 Client 확인 1
fail2ban-client status sshd
# 차단된 Client 확인 2
ipset --list
# 로그 보기
tail -f /var/log/fail2ban.log

방화벽

  • iptables : 프로토콜의 상태 추적, 패킷 애플리케이션 계층검사, 속도 제한, 필터링 정책을 명시하기 위한 매커니즘을 제공한다.
  • firewalld : iptables에 의해 제공되지만 관리자는 동적 방화벽 데몬, firewalld, 설정 도구를 통해 iptables와 상호 작용. 설정 도구에는 firewall-config, firewall-cmd, firewall-applet이 있음
  • /usr/lib/firewalld 및 /etc/firewalld
  • firewalld를 사용한다.
sudo su -
systemctl status firewalld
systemctl enable firewalld
systemctl start firewalld
  • ZONE 목록과 정책
# ZONE 목록
firewall-cmd  --get-zones

block dmz drop external home internal public trusted work

# ZONE 정책 확인
firewall-cmd --list-all-zones

# 활성화된 ZONE 확인
firewall-cmd --get-active-zone

# 특정 Zone의 설정확인
firewall-cmd --list-all --zone work

# 활성화된 Zone 만 설정 확인
firewall-cmd --list-all

# 기본 ZONE 설정 바꾸기
firewall-cmd  --set-default-zone=dmz

#  NIC 마다 다른 zone 을 설정
firewall-cmd --zone=dmz --change-interface=eth0
  • 서비스 관리
# 새로운 ZONE 생성
firewall-cmd --permanent --new-zone=webserver
firewall-cmd --reload

# Default Zone 설정
firewall-cmd  --set-default-zone=webserver

# 서비스 추가
firewall-cmd --permanent --zone=webserver --add-service=http

# 서비스 삭제
firewall-cmd --permanent --zone=webserver --remove-service=http
  • 사전정의되지 않은 서비스를 위한 포트 추가
firewall-cmd --permanent --zone=webserver --add-port=9090-9100/tcp
firewall-cmd --permanent --zone=webserver --remove-port=9090-9100/tcp
  • TODO: ufw 설정관련 내용 추가

SSH 보안 설정

  • PermitRootLogin no: Root 로 SSH 접속을 막아야 함
  • PubkeyAuthentication yes: SSH-Key를 통한 접속 허용
  • PasswordAuthentication no: SSH-Key만 사용하고 패스워드는 사용하지 못하도록 설정
  • Port 2222 : 알려진 포트를 변경
vi /etc/ssh/sshd_config
# Port 22 -> Port 2222

키 생성

nuri 계정에서 다음과 같이 키를 생성한다. Private Key를 다운받아 사용한다. Private key 에 PassPhrase는 관리대장 암호로 설정하였다.

ssh-keygen -t rsa -b 4096
cd ~/.ssh
cat id_rsa.pub >> authorized_keys
touch known_hosts

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts

Warning

이 키 파일을 다른 사용자에게 전달하거나 하지 말것. 필요시 새로 키를 생성한 후 해당 키를 전달하고 작업이 끝나면 authorized_keys에서 삭제할 것.

firewall-cmd --permanent --zone=public --add-port=2222/tcp
firewall-cmd --reload
semanage port -a -t ssh_port_t -p tcp 2222
systemctl restart sshd

SELinux 사용 (CentOS)

CentOS7 등 에서 SELinux를 기본 사용하도록 설정한다.

  • 동작 모드 확인
getenforce
sestatus
# permissive (감시) 모드
setenforce 0

모드 설정

  • /etc/sysconfig/selinux는 부팅시 SELinux 모드와 타입을 결정하다. /etc/selinux/config와 심볼릭 링크되어 있다.
  • Permissive나 Enforcing 모드 중 하나로 설정한다. disabled 사용 금지
vi /etc/sysconfig/selinux
# SELINUX=permissive

설정 변경후 시스템을 재부팅해야 반영이 가능하다.

SELinux boolean

보안 정책 설정 편의를 위해 사전에 정의된 규칙 집합

# 현재 설정확인
getsebool -a | egrep 'httpd(.*)mail'

setsebool -P httpd_can_sendmail true

주의사항

  • mv로 파일을 이동할 경우 원래 파일의 보안 컨텍스트를 유지
  • cp는 대상 파일이 복사되는 목적지 폴더의 기본 보안 컨텍스트를 따르게 됨

관련 명령어

  • chcon : change context, 객체의 보안 컨텍스트를 직접 지정한는 명령어
  • 재귀적으로 처리하는 -R 옵션
  • 타입을 지정하는 -t 옵션
  • restorecon : 잘못 설정된 파일과 디렉터리를 보안 정책에 맞도록 컨텍스트를 설정
  • 재귀적으로 처리하는 -R
  • 제외할 디렉터리를 지정하는 -e 옵션, 뒤에는 제외할 디렉터리 이름을 지정
  • matchpathcon : 디렉터리별로 필요한 보안 컨텍스트를 알아 낼 수 있음
  • 보안 컨텍스트를 알아낼 디렉터리의 경로를 적으면 됨
  • 기본 설정 컨텍스트와 일치하는지 검증하려면 대문자 -V 옵션을 주고 실행
chcon -R -t httpd_sys_content_t /var/www/html/hello.html
ls -lZ
restorecon -R /var/www/html/hello.html
matchpathcon -V /var/www/*

semanage

yum install -y policycoreutils-python

semanage port  -l | grep ssh
semanage port -a -p tcp -t ssh_port_t 2222
semanage port -d -p tcp 2222
  • 주요 디렉터리 경로마다 자동으로 특정 컨텍스트를 부여하도록 사전 탑재 정책에 설정되어 있습
# 설정된 파일 컨텍스트의 목록을 표시
semanage fcontext -l|grep httpd_sys_content_t

# 컨텍스트를 추가
semanage fcontext -a -t mysqld_db_t "/opt/mysql(/.*)?"
restorecon -R -v /opt/mysql

# 파일 컨텍스트 삭제
semanage fcontext -d "/opt/mysql(/.*)?"

setools

yum install setools-console
  • avcstat : 부팅 이후 AVC(Access Vector Cache) 에 대한 간략한 통계를 보여주는 명령어
  • seinfo : 정책 클래스 갯수, 타입, 허용하는 규칙등 SELinux 의 보안 정책을 조회하고 보고서를 출력
  • --portcon 옵션: 포트 번호에 할당된 보안 컨텍스트를 확인
  • --protocol 옵션:
  • sesearch : seinfo 보다 더 세밀한 규칙으로 조회
  • --allow(줄여서 -A) : 허용하는 정책을 조회
  • -s : 소스 컨텍스트를 지정
  • -t : 타겟 컨텍스트를 지정

  • findcon : SELinux context 를 검색해 주는 유틸리티, findcon FCLIST [OPTIONS] [EXPRESSION]

  • directory : 해당 디렉토리와 그 하위 디렉터리에서 주어진 조건에 맞는 정책을 검색

  • file_contexts : FCLIST가 file_contexts 파일의 이름(예: /etc/selinux/targeted/contexts/files/file_contexts) 이면 해당 정책 파일에서 일치하는 항목을 검색

  • database : indexcon 또는 apol 이라는 SELinux 정책 유틸리티의 실행으로 생성된 데이타 베이스를 분석할 경우에 사용

avcstat 3
seinfo --portcon=443 --protocol=tcp
sesearch -d --allow  -s httpd_t -t httpd_sys_rw_content_t
findcon .
findcon -t httpd_sys_rw_content_t /var/www/
ls -RlaZ

보고서

audit2why < /var/log/audit/audit.log

setroubleshoot-server

yum install setroubleshoot-server -y
systemctl restart messagebus

sealert -a /var/log/audit/audit.log

SSL 설정

아래와 같은 조건을 가정하여 설치를 한다.

  • 도메인 : nuri.example.com
  • 암호 : nuri

환경 설정

Java 설치

Java 가 설치되어 있어야 한다. root 사용자 RC에 다음을 포함해야 한다.

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

CertBot 설치

wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot

인증서

인증서 생성

sudo ./certbot-auto certonly --standalone -d nuri.example.com
sudo certbot certonly --standalone -d nuri.example.com
설치과정
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): nuri@example.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for nuri.example.com
Cleaning up challenges
Problem binding to port 80: Could not bind to IPv4 or IPv6.

IMPORTANT NOTES:
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.

인증서 설치

sudo su -
cd $JAVA_HOME

Private Key와 키 체인을 갖는 PKCS12 파일을 생성

openssl pkcs12 -export -out /tmp/nuri.example.com_fullchain_and_key.p12 -in /etc/letsencrypt/live/nuri.example.com/fullchain.pem -inkey /etc/letsencrypt/live/nuri.example.com/privkey.pem -name jira

PKS12을 JKS로 변환

keytool -importkeystore -deststorepass nuri -destkeypass nuri -destkeystore jira.jks -srckeystore /tmp/nuri.example.com_fullchain_and_key.p12 -srcstoretype PKCS12 -srcstorepass nuri -alias jira

인증서 적용하기 예제

인증서 갱신

  • letsencrypt 인증서는 유효기간이 3개월이다.
  • 3개월 마다 갱신을 해주어야 한다.
certbot renew --dry-run

이상이 없으면

certbot renew

  1. CentOS 7.X을 기본 대상으로 설명한다. 

  2. Ubuntu 18.04를 기본 대상으로 설명한다. 

댓글