ㅁ working with selinux


주요 SELinux 패키지의 개요를 설명

패키지 설치 및 업데이트, 사용되는 로그파일, 주요 SELinux 설정, SELinux 활성화 미 비 활성화, SELinux 모드 설정파일 및 디렉토리 레이블 임시 및 영구 변경, mount 명령으로 파일 시스템 레이블 덮어 쓰기, NFS 볼륨 마운트, 파일 및 디렉토리의 복사 및 보관시 SELinux 설정 방법



ㅁ SELinux Packages


설치중 수동으로 제외하는 경우를 빼곤 기본으로 SELinux 패키지가 설치 됩니다. 

Text 모드에서 최소 설치라도, 기본적으로 policycoreutils-python 과 policycoreutils-gui 설치되어 있음

기본적으로 SELinux 대상 정책이 적용, SELinux 가 enforcing 모드에서 실행

다음의 SELinux 패키지는 기본 설치


policycoreutils -> restorecon, secon, setfiles, semodule, load_policy, setsebool 제공


selinux-policy -> SELinux Reference 정책 설정을 제공

SELinux Reference 정책은 완전한 SELinux 정책에서 SELinux 대상 정책 등 다른 정책의 기반으로 사용되는 정책

해당 패키지는 selinux-policy.conf 파일과 RPM 매크로가 포함되어 있음

자세한 내용은 https://github.com/TresysTechnology/refpolicy/wiki 참조


selinux-policy-targeted -> SELinux 대상 정책을 제공

libselinux는 SELinux 응용 프로그램 API를 제공


libselinux-utils -> avcstat, getenforce, getsebool, matchpathcon, selinuxconlist, selinuxdefcon, selinuxenabled, setenforce 유틸리티를 제공


libselinux-python -> SELinux 응용 프로그램 개발 용 python 바인딩을 제공

기본으로 설치되지는 않지만 yum install <package-name> 명령을 실행하면 옵션으로 설치 가능


selinux-policy-devel -> 사용자 정의 SELinux 정책 및 정책 모듈 생성을 위한 유틸리티를 제공, SELinux와 다른 서비스를 맞게 설정하는 방법을 설명하는 MAN 페이지도 포함


selinux-policy-mls -> MLS SELinux 정책을 제공


setroubleshoot-server -> SELinux 액세스를 거부했을때 생성되는 거무 메시지를 sealert 유틸리티에서 볼수 있는 자세한 설명으로 변환, 패키지로 제공


setools-console -> 정책 분산 및 쿼리 감사 로그 모니터링 및 보고, 파일 컨텍스트 관리를 위한 다양한 유틸리티 및 라이브러리 Tresys Technology SETools distribution를 제공

setools 패키지는 SETools의 메타 패키지

setools-gui 패키지는 apol 및 seaudit의 각 유틸리티를 제공

setools-console 패키지는 sechecker, sediff, seinfo, sesearch, findcon 각 명령 줄 유틸리티를 제공

자세한 내용은 https://github.com/TresysTechnology/setools3/wiki 참조


setools 과 setools-gui의 각 패키지는 Redhat Network Optional 채널이 활성화 되어있을 때만 사용할수 있음

자세한 내용은 https://access.redhat.com/support/offerings/production/scope_moredetail 참조


mcstrans 는 s0-s0 : C0.c1023 같은 수준을 SystemLow-SystemHigh 등 읽기 쉬운 형식으로 변환


policycoreutils-python -> SELinux 의 조작 및 관리를 위한 semanage, audit2allow, audit2why, chcat 등 각종 유틸을 제공

policycoreutils-gui -> SELinux 관리 용 그래픽 유틸리티인 system-config-selinux를 제공



ㅁ which log file is used


dbus, audit 패키지는 기본 패키지 선택에서 제거하지 않으면 기본 설치

setroubleshoot-server 는 yum을 이용해서 설치, yum install setroubleshoot


auditd 가 실행중이면 다음과 같은 SELinux deny log는 /var/log/audit/audit.log에 기록


type=AVC msg=audit(1223024155.684:49): avc:  denied  { getattr } for  pid=2000 comm="httpd" path="/var/www/html/file1" dev=dm-0 ino=399185 scontext=unconfined_u:system_r:httpd_t:s0 tcontext=system_u:object_r:samba_share_t:s0 tclass=file

/var/log/message 에 기록되는 내용


May 7 18:55:56 localhost setroubleshoot: SELinux is preventing httpd (httpd_t) "getattr" to /var/www/html/file1 (samba_share_t). For complete SELinux messages. run sealert -l de7e30d6-5488-466d-a606-92c9f40d316d

setroubleshootd 는 서비스로 실행되지 않음

AVC 메시지 분석은 사용됨

필요에 따라 다음의 두가지 프로그램이 setroubleshoot 시작하는 방법으로 작동


sedispatch 유틸리티는 audit 서브 시스탬의 일부로 실행

AVC 거부 메시지가 반환되면 sedispatch는 dbus를 사용해서 메시지를 발송

setroubleshootd가 실행중이면 발송, 실행중이지 않으면 sedispatch가 자동으로 시작됨


seapplet 유틸리티는 시스템 도구 모음에서 실행

setroubleshootd의 dbus 메시지를 대기

알림 버블을 시작하여 사용자가 AVC 메시지를 확인 할수 있도록 지원


 - daemon 자동 시작


auditd 및 rsyslog 데몬을 자동시작 하려면, root 다음의 명령어 실행


~]# systemctl enable auditd.service
~]# systemctl enable rsyslog.service

정확한 동작 확인


~]$ systemctl is-enabled auditd
enabled
~]$ systemctl is-enabled rsyslog
enabled

systemctl status service-name.service 명령을 사용해서 enabled 검색


~]$ systemctl status auditd.service | grep enabled
auditd.service - Security Auditing Service
   Loaded: loaded (/usr/lib/systemd/system/auditd.service; enabled)

systemd 데몬 시스템 서비스를 관리하는 방법은 다음 링크에서 확인


https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sect-Managing_Services_with_systemd-Services.html

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/index.html


 - 주요 설정 파일


/etc/selinux/config 주요 SELinux 설정 파일

SELinux 모드 및 SELinux 정책을 관리


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

SELINUX = enforcing

SELinux는 enforcing, permissive, disabled 세가지 모드

enforcing - SELinux 정책이 적용, SELinux 정책 규칙에 따라 SELinux는 액세스를 거부, 거부메시지가 기록

permissve - SELinux 정책이 적용되지 않음, ecforcing모드에서 거부되는 동작은 기록됨

disabled - SELinux 비활성화된 SELinux, 모듈이 Linux 커널에 등록되지 않음, DAC 규칙만 사용


SELINUXTYPE = targeted

SELINUXTYPE 옵션은 사용하는 SELinux 정책을 설정

대상 정책이 기본 정책

MLS 정책을 사용하는 경우에만 옵션을 변경

MLS 정책의 활성화에 대해선 https://access.redhat.com/documentation/ja-JP/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide/mls.html#enabling-mls-in-selinux 참조


중요!!!


SELinux 모드중 permissive, disabled 모드에서 시스탬이 실행하게되면, 파일에 잘못된 레이블을 하는 권한이 있음

SELinux를 사용하지 않는동안 생성된 파일에는 레이블이 없음

enforcing 모드로 변경하면 이것이 문제가 될수 있음

표시가 잘못된 파일과, 레이블이 없는 파일이 문제를 일으키지 않게하기위해 disabled모드에서 permissive 모드와 enforcing 모드로 변경하면 파일시스탬에서 자동으로 재 분류가 진행


 - SELinux 활성화 및 비 활성화


SELinux 상태를 확인하려면, setenforce 또는 sestatus 명령을 사용, getenforce 명령은 enforcing, pemissive, disabled 중 하나를 반환

sestatus 명령은 SELinux 상태 및 사용된 SELinux 정책을 반환


~]$ sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 24
Policy from config file:        targeted

PS.

시스템을 처음 설치시 SELinux가 없을시, 특히 selinux-policy 패키지업이 설치된 경우 SELinux를 활성화 하려면 추가 작업이 필요

dracut 유틸리티를 실행, initramfs 파일 시스템에 SELinux를 기재해야 함


SELinux가 비활성화 되어있는경우 /etc/selinux/config 에 SELINUX = disabled 설정이 되어 있음


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

getenforce 명령을 하면 disabled을 반환


~]$ getenforce
Disabled

다음 단계에서 SELinux를 사용



 - SELinux의 활성화


다음의 패키지가 설치되어 있다는것을 전제로 진행


selinux-policy-targeted, selinux-policy, libselinux, libselinux-python, libselinux-utils, policycoreutils, policycoreutils-python, setroubleshoot, setroubleshoot-server, setroubleshoot-plugins


rpm 명령어로 확인


~]$ rpm -qa | grep selinux
selinux-policy-3.12.1-136.el7.noarch
libselinux-2.2.2-4.el7.x86_64
selinux-policy-targeted-3.12.1-136.el7.noarch
libselinux-utils-2.2.2-4.el7.x86_64
libselinux-python-2.2.2-4.el7.x86_64
~]$ rpm -qa | grep policycoreutils
policycoreutils-2.2.5-6.el7.x86_64
policycoreutils-python-2.2.5-6.el7.x86_64
~]$ rpm -qa | grep setroubleshoot
setroubleshoot-server-3.2.17-2.el7.x86_64
setroubleshoot-3.2.17-2.el7.x86_64
setroubleshoot-plugins-3.0.58-2.el7.noarch

설치되어 있지 않다면 yum 으로 설치 진행


~]# yum install package_name

policycoreutils-gui, setroubleshoot, mcstrans


SELinux를 사용하기전에 파일시스템에 있는 모든 파일을 SELinux 문맥으로 레이블 해야함, 위의 작업이 완료되지 않으면 제한된 도메인 액세스가 거부될수 있음, 시스탬의 정상 부팅을 방해

 이를 방지하려면 /etc/selinux/config 파일에서 SELINUX = permissive 설정


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=permissive
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

시스탬을 다시시작, 이 과정에서 파일 시스템 레이블이 지정됨, 이 라벨 과정에서 모든 파일에 SELinux 문맥이 분류


~]# reboot
*** Warning -- SELinux targeted policy relabel is required.
*** Relabeling could take a very long time, depending on file
*** system size and speed of hard drives.
****

* 는 1000을 의미함

ex) **** 로 분류된 파일은 4000 파일을 나타냄

모든 파일에 레이블을 지정하는 시간은 파일수, 하드드라이브 속도에 따라 달라짐, 최신의 범용적인 시스탬에서는 대략 10분정도 소요


1차로 permissive 모드에서 검증을 하고 해당 모드에서 거부관련 로그가 없을때에 enforcing 모드로 변경

시스탬 시작시 SELinux가 액세스를 거부한 경우 

https://access.redhat.com/documentation/ja-JP/Red_Hat_Enterprise_Linux/7/html/SELinux_Users_and_Administrators_Guide/chap-Security-Enhanced_Linux-Troubleshooting.html

확인 필요


~]# grep "SELinux is preventing" /var/log/messages

/var/log/messages 파일에 거부 메시지가 없다면 /etc/selinux/config 에서 enforcing으로 설정


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

시스탬을 다시 시작하여 getenforce 에서 enforcing이 반환되는것을 확인


~]$ getenforce
Enforcing

root 로 SELinux 및 Linux 사용자 사이의 매핑을 확인, 출력은 다음과 같이 확인가능


~]# semanage login -l

Login Name           SELinux User         MLS/MCS Range        Service

__default__          unconfined_u         s0-s0:c0.c1023       *
root                 unconfined_u         s0-s0:c0.c1023       *
system_u             system_u             s0-s0:c0.c1023       *

이러한 출력이 되지 않는다면 root 다음과 같은 명령을 실행해서 사용자 매핑을 수정


SELinux-user username is already defined 경고는 무시

username은 unconfined_u, guest_u, xguest_u 중 하나임


 - 사용자 매핑 변경


  1. ~]# semanage user -a -S targeted -P user -R "unconfined_r system_r" -r s0-s0:c0.c1023 unconfined_u
  2. ~]# semanage login -m -S targeted -s "unconfined_u" -r s0-s0:c0.c1023 __default__
  3. ~]# semanage login -m -S targeted -s "unconfined_u" -r s0-s0:c0.c1023 root
  4. ~]# semanage user -a -S targeted -P user -R guest_r guest_u
  5. ~]# semanage user -a -S targeted -P user -R xguest_r xguest_u


 - SELinux 의 비활성화


/etc/selinux/config 파일의 SELINUX=disabled 변경


# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these two values:
#       targeted - Targeted processes are protected,
#       mls - Multi Level Security protection.
SELINUXTYPE=targeted

시스탬을 다시 시작하여 getenforce 명령이 disabled 을 반환하는지 확인


~]$ getenforce
Disabled

ㅁ booleans


booleans 을 사용하면 SELinux 정책 기술의 지식이 없이도 런타임시에 SELinux 정책의 일부를 변경이 가능

SELinux 정책을 다시 로드하거나 다시 컴파일 하지 않고, NFS 볼륨에 서비스를 허용하는 액세스를 변경하는것등이 가능함


 - booleans 목록


root 로 semanage boolean -l 명령을 실행, 다음의 예시는 모든 booleans 값이 표시되는것이 아니며, 출력은 생략되어 있음


~]# semanage boolean -l
SELinux boolean                State  Default Description

ftp_home_dir                   (off  ,  off)  Determine whether ftpd can read...
smartmon_3ware                 (off  ,  off)  Determine whether smartmon can...
mpd_enable_homedirs            (off  ,  off)  Determine whether mpd can traverse...

SELinux boolean - boolean 이름을 표시

Description - boolean 이 활성화 인지 비 활성화 인지, 무엇을 할것인지에 대해 표시


다음의 예시는 ftp_home_dir boolean off 에서 ftp 데몬 (vsftpd)가 사용자의 홈디렉토리에 있는 파일에 읽기/쓰기를 하지 않도록 되어 있음


ftp_home_dir                   (off  ,  off)  Determine whether ftpd can read...

getsetbool -a 명령은 boolean 값을 나열하고, 선택 여보를 표시하지만 개별 설명은 나오지 않음


~]$ getsebool -a
cvs_read_shadow --> off
daemons_dump_core --> on
ftp_home_dir --> off

getsebool boolean-name 실행하면 boolean-name 상태만을 나열


~]$ getsebool cvs_read_shadow
cvs_read_shadow --> off

여러 boolean 값을 표시하려면 공백으로 목록을 구분


~]$ getsebool cvs_read_shadow daemons_dump_core ftp_home_dir
cvs_read_shadow --> off
daemons_dump_core --> on
ftp_home_dir --> off


 - boolean 설정


setsebool 유틸리티로 setsebool boolean_name on/off 형식으로 실행


다음의 예시는 httpd_can_network_connect_db의 boolean 설정을 표시


httpd_can_network_connect_db boolean이 off이며, Apache http server 스크립트와 모듈이 데이터베이스 서버에 연결할 수 없도록 되어있음


~]$ getsebool httpd_can_network_connect_db
httpd_can_network_connect_db --> off

Apache http server 스크립트와 모듈이 일시적으로 데이터베이스 서버에 연결할 수 있도록 하려면 root 다음과 같은 명령어 실행


~]# setsebool httpd_can_network_connect_db on

boolean 값이 설정되어 있는지 확인하려면 getsebool 유틸을 사용


~]$ getsebool httpd_can_network_connect_db
httpd_can_network_connect_db --> on

이제 apache http server 스크립트 및 모듈이 데이터베이스 서버에 연결이 가능


해당 변경 내용은 유지되는 내용이 아님, 재부팅 이후에도 변경을 유지하려면 root로 setsebool -P boolean-name on 명령을 실행


~]# setsebool -P httpd_can_network_connect_db on

 - shell의 자동 완성 기능


getsebool, setsebool, semanage는 shell의 자동완성 기능을 사용가능

getsebool 및 setsebool 에서는 명령줄 매개변수 및 boolean 값으로 자동완성 기능을 사용할수 있음

명령줄 매개 변수만 나열하려면 명령이름 뒤에 하이픈 기호를("-") 지정하고 tab을 사용


~]# setsebool -[Tab]
-P

boolean 자동완성 기능을 사용하려면 boolean 이름을 입력을 시작하고 tab 키를 입력


~]$ getsebool samba_[Tab]
samba_create_home_dirs   samba_export_all_ro      samba_run_unconfined     
samba_domain_controller  samba_export_all_rw      samba_share_fusefs       
samba_enable_home_dirs   samba_portmapper         samba_share_nfs
~]# setsebool -P virt_use_[Tab]
virt_use_comm     virt_use_nfs      virt_use_sanlock  
virt_use_execmem  virt_use_rawip    virt_use_usb      
virt_use_fusefs   virt_use_samba    virt_use_xserver

semanage 유틸리티는 여러 명령줄 인수로 사용되며, 이들은 하나씩 작섣됨

semanage 명령의 첫 번째 인수는 옵션에서 SELinux 정책의 어떤 부분을 관리하는 방법을 지정


~]# semanage [Tab]
boolean     export      import      login       node        port
dontaudit   fcontext    interface   module      permissive  user

이후에 명령줄 매개 변수가 계속됨


~]# semanage fcontext -[Tab]
-a           -D           --equal      --help       -m           -o
--add        --delete     -f           -l           --modify     -S
-C           --deleteall  --ftype      --list       -n           -t
-d           -e           -h           --locallist  --noheading  --type
~]# semanage fcontext -a -t samba<tab>
samba_etc_t                     samba_secrets_t
sambagui_exec_t                 samba_share_t
samba_initrc_exec_t             samba_unconfined_script_exec_t
samba_log_t                     samba_unit_file_t
samba_net_exec_t
~]# semanage port -a -t http_port_t -p tcp 81

 - SELINUX 파일의 레이블 context


SELinux 실행중인 시스탬에서 모든 프로세스와, 파일에 라벨을 붙일수 있음

SELinux context 라고 지칭

ls -Z 명령어로 확인가능


~]$ ls -Z file1
-rw-rw-r--  user1 group1 unconfined_u:object_r:user_home_t:s0 file1

SELinux 사용자의 unconfined_u -> role, object_r type, user_home_t의 level(s0) 을 확인

이 정보는 접근 제한 결정에 사용

DAC는 Linux UID, GID에 따라 제어됨

SELinux 정책 규칙은 DAC 규칙 이후에 확인

DAC 규칙이 먼저 액세스를 거부하면 SELinux 정책은 사용되지 않음


 - note

기본적으로 파일 및 디렉토리는 부모 디렉토리의 SELinux 유형을 상속

/etc/ 디렉토리에 새파일을 작성하면 etc_t 유형의 레이블을 상속


~]$ ls -dZ - /etc/
drwxr-xr-x. root root system_u:object_r:etc_t:s0       /etc
~]# touch /etc/file1
~]# ls -lZ /etc/file1
-rw-r--r--. root root unconfined_u:object_r:etc_t:s0   /etc/file1

SELinux context를 관리하는 명령어에는 chcon, semanage fcontext, restorecon 등이 있음



 - chmod 임시로 변경


chmod 로 SELinux context 를 수정, chcon 명령에 의한 변경 내용은 시스템 레이블 혹은 restorecon 명령이 실행될때에 유지되지 않음

SELinux 정책은 특정 파일의 SELinux context 를 사용자가 수정할수 있는지 여부를 제어

chcon을 사용하면 사용자는 변경된 SELinux context 일부 혹은 전부를 제공, SELinux 작업이 안되는경우 파일 형식이 잘못되어 있을수 있음



chcon -t type file-name -> file type


file-name은 파일이 될수도 있고 디렉토리도 될수 있음, file-name의 selinux type을 httpd_sys_content_t 로 변경하는 예

  • ~]$ chcon -t httpd_sys_content_t file-name
chcon -R 옵션은 디렉토리 와 안의 contents 까지 같이 변경함
  • ~]$ chcon -R -t httpd_sys_content_t directory-name

4.6 파일과 디렉토리 type 변경


home 디렉토리에 들어가서 파일을 생성호 SELinux 를 확인



~]$ touch file1
~]$ ls -Z file1
-rw-rw-r--  user1 group1 unconfined_u:object_r:user_home_t:s0 file1

file1 은 unconfined_u user, object_r role, user_home_t type으로 되어 있으며, s0의 level을 가지고 있음


chcon 명령어를 이용해서 samba_share_t type으로 type을 변경 옵션은 -t 를 사용


~]$ chcon -t samba_share_t file1
~]$ ls -Z file1 
-rw-rw-r--  user1 group1 unconfined_u:object_r:samba_share_t:s0 file1

restorecon -v 를 이용해서 SELinux를 복구


~]$ restorecon -v file1
restorecon reset file1 context unconfined_u:object_r:samba_share_t:s0->system_u:object_r:user_home_t:s0

4.7 디렉토리 및 그 및의 contents  type 변경


/web 디렉토리 생성후 file1, 2, 3을 /web/ 에 생성 files의 기본 label은 default_t type


~]# mkdir /web
~]# touch /web/file{1,2,3}
~]# ls -dZ /web
drwxr-xr-x  root root unconfined_u:object_r:default_t:s0 /web
~]# ls -lZ /web
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file1
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file2
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file3


root 로 /web/ 디렉토리에 httpd_sys_content_t type으로 변경


~]# chcon -R -t httpd_sys_content_t /web/
~]# ls -dZ /web/
drwxr-xr-x  root root unconfined_u:object_r:httpd_sys_content_t:s0 /web/
~]# ls -lZ /web/
-rw-r--r--  root root unconfined_u:object_r:httpd_sys_content_t:s0 file1
-rw-r--r--  root root unconfined_u:object_r:httpd_sys_content_t:s0 file2
-rw-r--r--  root root unconfined_u:object_r:httpd_sys_content_t:s0 file3

restorecon 으로 원상복구


~]# restorecon -R -v /web/
restorecon reset /web context unconfined_u:object_r:httpd_sys_content_t:s0->system_u:object_r:default_t:s0
restorecon reset /web/file2 context unconfined_u:object_r:httpd_sys_content_t:s0->system_u:object_r:default_t:s0
restorecon reset /web/file3 context unconfined_u:object_r:httpd_sys_content_t:s0->system_u:object_r:default_t:s0
restorecon reset /web/file1 context unconfined_u:object_r:httpd_sys_content_t:s0->system_u:object_r:default_t:s0

semanage fcontext 명령어로 SELinux context를 수정 /etc/selinux/targeted/contexts/files/ 


semanage fcontext SELinux context of files을 수정

/etc/selinux/targeted/contexts/files/ directory에 생성



~]# semanage fcontext -a options file-name|directory-name
~]# restorecon -v file-name|directory-name



~]# touch /etc/file1
~]$ ls -Z /etc/file1
-rw-r--r--  root root unconfined_u:object_r:etc_t:s0       /etc/file1



~]$ ls -dZ directory_name


~]# semanage fcontext -a -t samba_share_t /etc/file1
~]# ls -Z /etc/file1 
-rw-r--r--  root root unconfined_u:object_r:etc_t:s0       /etc/file1


/etc/file1    unconfined_u:object_r:samba_share_t:s0
~]# restorecon -v /etc/file1
restorecon reset /etc/file1 context unconfined_u:object_r:etc_t:s0->system_u:object_r:samba_share_t:s0



~]# mkdir /web
~]# touch /web/file{1,2,3}
~]# ls -dZ /web
drwxr-xr-x  root root unconfined_u:object_r:default_t:s0 /web
~]# ls -lZ /web
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file1
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file2
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file3


~]# semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
~]$ ls -dZ /web
drwxr-xr-x  root root unconfined_u:object_r:default_t:s0 /web
~]$ ls -lZ /web 
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file1
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file2
-rw-r--r--  root root unconfined_u:object_r:default_t:s0 file3


/web(/.*)?    system_u:object_r:httpd_sys_content_t:s0
~]# restorecon -R -v /web
restorecon reset /web context unconfined_u:object_r:default_t:s0->system_u:object_r:httpd_sys_content_t:s0
restorecon reset /web/file2 context unconfined_u:object_r:default_t:s0->system_u:object_r:httpd_sys_content_t:s0
restorecon reset /web/file3 context unconfined_u:object_r:default_t:s0->system_u:object_r:httpd_sys_content_t:s0
restorecon reset /web/file1 context unconfined_u:object_r:default_t:s0->system_u:object_r:httpd_sys_content_t:s0





~]# semanage fcontext -d "/web(/.*)?"
~]# semanage fcontext -d file-name|directory-name
/test    system_u:object_r:httpd_sys_content_t:s0
~]# semanage fcontext -d /test











'Security > Linux - Selinux' 카테고리의 다른 글

selinux 03  (0) 2016.08.01
selinux 01, 02  (0) 2016.06.30


ㅁ TARGETED POLICY

ㅁ 제한하는 프로세스


Redhat linux는 sshd 및 httpd 같은 네트워크에서 수신하는 서비스는 거의 모든 제한이 있습니다.

또한 passwd util등의 root 사용자로 실행하고 사용자에 대한 작업을 수행하는 프로세스는 거의 제한이 있습니다.


프로세스에 제한이 있는 프로세스 자체 도메인에서 실행됩니다. 


httpd_t 도메인에서 httpd 프로세스가 실행되는 등등 입니다. 

제한이 있는 프로세스가 공격자에 의해 위험에 처해도 SELinux 정책 설정에 따라 공격자의 소스에 대한 액세스와 공격으로 인한 손상은 제한됩니다.



ㅁ SELinux 상태 확인 방법


SELinux 활성화 enforcing 모드에서 실행되고, 해당 정책이 사용되고 있는지 확인, 정상적인 출력은 아래와 같음


~]$ sestatus
SELinux status:                 enabled
SELinuxfs mount:                /selinux
Current mode:                   enforcing
Mode from config file:          enforcing
Policy version:                 24
Policy from config file:        targeted

root로 /var/www/html/ 디렉토리에 파일을 생성


~]# touch /var/www/html/testfile

생성된 파일의 SELinux 확인


~]$ ls -Z /var/www/html/testfile       
-rw-r--r--  root root unconfined_u:object_r:httpd_sys_content_t:s0 /var/www/html/testfile

기본적으로 Linux 사용자는 제한이 없음

testfile 파일에 SELinux unconfined_u 사용자의 라벨이 붙어 있음


RBAC는 파일이 아닌 프로세스에 사용됨, 역활은 파일에게 의미가 없음

object_r 역할은 파일에 사용되는 일반적인 역할

/proc/ 디렉토리 아래에서는 프로세스와 관련된 파일은 system_r role을 사용하는 경우가 있음

httpd_sys_content_t 타입은 httpd 프로세스가 파일에 액세스 할수 있도록 허용


 - Samba가 사용하는 파일등 정확하게 분류되지 않은 파일을 apache http server (httpd)가 읽는것을 방지하는 정책

SELinux의 방지 예시를 보여줌, 이것은 어디까지 예시이며, 실운영 환경에서는 사용하지 말것


httpd 및 wget 패키지가 설치 되어 있음, SELinux 대상 정책이 사용되고, SELinux 가 enforcing 모드에서 실행되는것을 전제로 진행


ㅁ 프로세스 제한하는 예시


root로 httpd 데몬을 시작


~]# systemctl start httpd.service

서비스가 실행되고 있는지 확인

출력은 다음과 같음, 타임스탬프만 다름


~]$ systemctl status httpd.service
httpd.service - The Apache HTTP Server
	  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled)
	  Active: active (running) since Mon 2013-08-05 14:00:55 CEST; 8s ago

Linux 사용자의 쓰기 권한이 있는 디렉토리로 전환 한후 다음 명령을 실행

기본 설정에 변경이 없으면 이 명령은 성공함


~]$ wget http://localhost/testfile
--2009-11-06 17:43:01--  http://localhost/testfile
Resolving localhost... 127.0.0.1
Connecting to localhost|127.0.0.1|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 0 [text/plain]
Saving to: `testfile'

[ <=>                              ] 0     --.-K/s   in 0s
		
2009-11-06 17:43:01 (0.00 B/s) - `testfile' saved [0/0]

chcon 명령으로 파일의 레이블을 변경

파일 시스템의 레이블이 바꿔 질이 변경 사항이 손실

파일 시스템 레이블이 바꿔진 경우 이러한 변경으르 영구적으로 유지 하려면 semanage 유틸리티를 사용

이 명령에 대해서는 추후 설명

root 로 다음 명령을 실행하여 유형을 samba에서 사용되는 유형으로 변경


~]# chcon -t samba_share_t /var/www/html/testfile

변경된것을 확인하려면 다음과 같은 명령어를 실행


~]$ ls -Z /var/www/html/testfile
-rw-r--r--  root root unconfined_u:object_r:samba_share_t:s0 /var/www/html/testfile

현재 DAC 권한은 httpd 프로세스에 의한 testfile에 대한 액세스를 허용하는 것에 유의하십시요

사용자로의 쓰기 권한이 있는 디렉토리로 전환 한 후 다음 명령을 실행합니다. 

기본 설정에 변경이 없으면 이 명령은 실패합니다. 


~]$ wget http://localhost/testfile
--2009-11-06 14:11:23--  http://localhost/testfile
Resolving localhost... 127.0.0.1
Connecting to localhost|127.0.0.1|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2009-11-06 14:11:23 ERROR 403: Forbidden.

root 로 testfile을 삭제


~]# rm -i /var/www/html/testfile

httpd 실행이 필요하지 않은 경우 root로 다음 명령을 실행 중지


~]# systemctl stop httpd.service

이 예에서는 SELinux에서 추가 된 새로운 보안을 설명

2단계에서는 DAC 규칙을 httpd 프로세스에 의한 testfile에 대한 액세스를 허용

파일은 httpd 프로세스에 권한 없는 유형으로 분류되어 있기 때문에, SELinux가 액세스를 거브

auditd 데몬이 실행되면 다음과 같은 오류가 /var/log/audit/audit.log에 기록


type=AVC msg=audit(1220706212.937:70): avc:  denied  { getattr } for  pid=1904 comm="httpd" path="/var/www/html/testfile" dev=sda5 ino=247576 scontext=unconfined_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:samba_share_t:s0  tclass=file

type=SYSCALL msg=audit(1220706212.937:70): arch=40000003 syscall=196 success=no exit=-13 a0=b9e21da0 a1=bf9581dc a2=555ff4 a3=2008171 items=0 ppid=1902 pid=1904 auid=500 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=1 comm="httpd" exe="/usr/sbin/httpd" subj=unconfined_u:system_r:httpd_t:s0 key=(null)

또한 다음과 같은 오류가 /var/log/httpd/error_log 에 기록


[Wed May 06 23:00:54 2009] [error] [client 127.0.0.1] (13)Permission denied: access to /testfile denied


ㅁ 제한이 없는 프로세스


제한없는 프로세스가 제한되지 않는 도메인에서 실행됩니다.

예를들면 init에서 실행되는 제한이 없는 서비스는 unconfined_service_t 

도메인에서 커널에서 실행되는 제한이 없는 서비스는 kernel_t 

도메인에 제한이 없는 Linux 사용자에 의해 실행되는 제한이 없는 서비스는 unconfined_t 도메인에서 실행되는 수 있습니다. 


SELinux 활성화 되어 있는지 확인, 실행방법은 위의 SELinux 상태 확인방법을 확인


제한없이 실행중인 경우 apache http server (httpd)가 samba를 위한 데이터에 액서스 할 수 있는 모습을 보여줌

httpd 프로세스는 제한된 httpd_t 도메인에서 실행되는 것을 명심할것

이것은 어디까지 예시입니다. 

httpd, wget, dbus, audit 패키지가 설치되어 SELinux 대상 정책이 사용됨

SELinux가 enforcing 모드에서 실행되는 것을 전제로 하고 있음


- 제한없는 프로세스의 예시


chcon 명령으로 파일의 레이블을 변경

파일 시스템의 레이블이 바꿔 질이 변경 사항은 손실

파일 시스템 레이블이 바꿔진 경우 이러한 변경을 영구적으로 유지하려면 semanage 유틸리티를 사용

root 로 다음 명령을 실행하여 유형을 Samba에서 사용되는 유형으로 변경


~]# chcon -t samba_share_t /var/www/html/testfile

변경을 표시합니다.


~]$ ls -Z /var/www/html/testfile
-rw-r--r--  root root unconfined_u:object_r:samba_share_t:s0 /var/www/html/testfile

다음 명령을 실행하여 httpd 프로세스가 실행되고 있지 않은지 확인


~]$ systemctl status httpd.service
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled)
   Active: inactive (dead)

다른 내용이 나온다면 root 사용자로 다음명령을 실행하여 httpd 프로세스를 중지


~]# systemctl stop httpd.service

httpd 프로세스를 제한없이 실행하려면 root 사용자로 다음 명령을 실행하여 /usr/sbin/httpd 파일의 유형을 제한하는 도메인으로 마이그레이션 하지 않은 것으로 변경


~]# chcon -t bin_t /usr/sbin/httpd

/usr/sbin/httpd 에 bin_t 유형이 분류되어 있는지 확인


~]$ ls -Z /usr/sbin/httpd
-rwxr-xr-x. root root system_u:object_r:bin_t:s0       /usr/sbin/httpd

root 로 httpd 프로세스를 시작, 성공적으로 시작되었는지 확인


~]# systemctl start httpd.service
~]# systemctl status httpd.service
httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled)
   Active: active (running) since Thu 2013-08-15 11:17:01 CEST; 5s ago

다음 명령을 실행하여, httpd가 unconfined_service_t 도메인에서 실행되고 있는지 확인


~]$ ps -eZ | grep httpd
system_u:system_r:unconfined_service_t:s0 11884 ? 00:00:00 httpd
system_u:system_r:unconfined_service_t:s0 11885 ? 00:00:00 httpd
system_u:system_r:unconfined_service_t:s0 11886 ? 00:00:00 httpd
system_u:system_r:unconfined_service_t:s0 11887 ? 00:00:00 httpd
system_u:system_r:unconfined_service_t:s0 11888 ? 00:00:00 httpd
system_u:system_r:unconfined_service_t:s0 11889 ? 00:00:00 httpd

Linux 사용자의 쓰기 권한이 있는 디렉토리로 전환 한 후 다음 명령을 실행합니다. 기본설정에 변경이 없으면 이명령을 성공함


~]$ wget http://localhost/testfile
--2009-05-07 01:41:10--  http://localhost/testfile
Resolving localhost... 127.0.0.1
Connecting to localhost|127.0.0.1|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 0 [text/plain]
Saving to: `testfile.1'

[ <=>                            ]--.-K/s   in 0s      
	
2009-05-07 01:41:10 (0.00 B/s) - `testfile.1' saved [0/0]

httpd 프로세스는 samba_share_t 유형의 라벨이 붙은 파일에 액세스하지 않지만 httpd는 제한없는 unconfined_service_t 도메인에서 실행하고 있으며, DAC 규칙을 대체

wget 명령을 성공함, 만약 httpd가 제한된 httpd_t 도메인에서 실행되면, wget 명령은 실패했을것 입니다. 



restorecon 유틸리티는 파일의 기본 SELinux 문맥을 복원함

root 다음 명령을 실행하면 /usr/sbin/httpd의 기본 SELinux 문맥이 복원


~]# restorecon -v /usr/sbin/httpd
restorecon reset /usr/sbin/httpd context system_u:object_r:unconfined_exec_t:s0->system_u:object_r:httpd_exec_t:s0

/usr/sbin/httpd에 httpd_exec_t 유형이 분류되어 있는지 확인


~]$ ls -Z /usr/sbin/httpd
-rwxr-xr-x  root root system_u:object_r:httpd_exec_t:s0 /usr/sbin/httpd

root 로 다음명령을 실행하여 httpd를 다시 실행

다시 시작되면 httpd가 제한된 httpd_t 도메인에서 실행하고 있는지 확인


~]# systemctl restart httpd.service
~]$ ps -eZ | grep httpd
system_u:system_r:httpd_t:s0    8883 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8884 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8885 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8886 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8887 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8888 ?        00:00:00 httpd
system_u:system_r:httpd_t:s0    8889 ?        00:00:00 httpd

root로 testfile을 삭제


~]# rm -i /var/www/html/testfile
rm: remove regular empty file `/var/www/html/testfile'? y

httpd 실행이 필요하지 않은경우 root로 다음 명령을 실행하여 httpd를 중지


~]# systemctl stop httpd.service

이 섹센의 예는 위험에 제한이 있는 과정에서 데이터가 어떻게 보호되는지, 위험에 제한이 없는 과정에서 공격자가 데이터에 엑세스가 쉬운가? 를 보여줍니다.


ㅁ CONFINED AND UNCONFINED USERS


user는 selinux 정책을 사용하여 selinux 사용자에 매핑이 됨

selinux 사용자에게 부과된 제한이 linux 사용자에게 상속이 됨


root 로 semanage login -l 실행하면 linux 사용자 매핑이 표시


~]# semanage login -l

Login Name           SELinux User         MLS/MCS Range        Service

__default__          unconfined_u         s0-s0:c0.c1023       *
root                 unconfined_u         s0-s0:c0.c1023       *
system_u             system_u             s0-s0:c0.c1023       *

linux 사용자는 기본적으로 __default__ Login에 매핑, unconfined_u 사용자에 매핑


__default__               unconfined_u              s0-s0:c0.c1023

신규 Linux 사용자 시스탬엠 추가, 사용자를 SELinux unconfined_u 사용자에 매핑하는 방법에 대한 설명

Linux default root 사용자가 제한없이 실행중이라는것을 전제로 진행


 - 신규 사용자의 SELinux unconfined_u 사용자에 매핑 시키기


~]# useradd newuser
~]# passwd newuser
Changing password for user newuser.
New UNIX password: Enter a password 
Retype new UNIX password: Enter the same password again 
passwd: all authentication tokens updated successfully.

logout 후에 새로 생성한 user로 로그인

pam_selinux PAM module이 자동으로 Linux 사용자를 SELinux 사용자에 매핑 (이번 경우는 unconfined_u)로 설정함

확인작업


[newuser@localhost ~]$ id -Z 
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

새로운 사용자를 삭제하려면


root로 userdel -r newuser 하게되면 삭제됨



Linux 사용자는 MCS, MLS에 제한을 받음


unconfined_t 도메인에서 자신의 제한된 도메인을 마이그레이션 진행

SELinux 정책에서 정의하고있는 응용 프로그램을 제한없이 Linux 사용자가 실행하면 이러한 제한이 없는 Linux 사용자는 제한이 있는 도메인의 제약에 영향을 받음


Linux 사용자가 제한이 없더라도 응용프로그램에는 여전히 제한이 존제한다라는것

응용프로그램의 취약점이 악용되더라도 정책에서 제한을 할수 있음


제한된 사용자는 각각 unconfined_t 도메인에 대해 제한된 사용자 도메인 제한이 됨


SELinux 정책은 제한된 사용자 도메인에 대해 자신의 목표에 제한이 있는 도메인으로의 전환을 정의 할 수 있음

제한된 Linux 사용자는 대상의 제한이 있는 도메인의 제약의 영향을 받게됨

특별한 권한이 역할에 따라 제한된 사용자와 관련이 있음


 - Linux 사용자 권한 표


UserRoleDomainX Window Systemsu or sudoExecute in home directory and /tmp/ (default)Networking
sysadm_usysadm_rsysadm_tyessu and sudoyesyes
staff_ustaff_rstaff_tyesonly sudoyesyes
user_uuser_ruser_tyesnoyesyes
guest_uguest_rguest_tnononono
xguest_uxguest_rxguest_tyesnonoFirefox only

user_t, guest_t, xguest_t 도메인 linux 사용자는 setuid 응용프로그램을 실행할수 없음 (ex. passwd)

su 나 sudo setuid 프로그램을 실행할수 없음으로 , 이 응용프로그램을 사용해서 root 가 될수 없음


sysadm_t, staff_t, user_t, xguest_t 도메인 Linux 사용자는 X Window system 및 console을 통해 로그인을 할수 있음


guest_t, xguest_t 도메인 Linux 사용자는 Default가 /tmp/ 내부의 응용프로그램을 실행할수 없음

쓰기 권한이 있는 디렉토리에 있는 응용 프로그램에서 사용자의 권한을 상속하는 응용 프로그램을 실행할수 없음

이렇게 하면 결함이 있는 응용프로그램이나 악성 어플리케이션이 사용자의 파일을 수정하지 못하도록 할수 있음


staff_t, user_t 도메인 linux 기본 사용자는 자신의 홈 디렉토리와 /tmp/ 에 있는 응용 프로그램의 실행이 가능


xguest_t 도메인 linux 사용자의 유일한 네트워크 액세스는 firefox 


 - 위의 SELinux 사용자 이외에 해당 사용자에 매핑할수 있는 특별한 역활이 있음, 이러한 SELinux는 사용자에게 부여하는것을 결정


webadm_r 은 apache http 서버 관련 selinux 유형의 처리만 가능

dbadm_r 은 MariaDB 및 PostgreSQL 관리 시스탬 관련 SELinux 유형의 처리만 가능

logadm_r 은 syslog 및 auditlog 프로세스 관련 SELinux 유형의 처리만 가능

sysadm_r 은 selinux 처리만 가능

auditadm_r 은 audit 서브 시스템에 관련된 프로세스의 처리만 가능


 - 사용 가능한 역할을 나열


~]$ seinfo -r

seinfo 는 setools-console 패키지를 설치해야함


ㅁ The sudo Transition and SELinux Roles


제한된 사용자가 root 권한을 필요로하는 관리 작업을 수행해야 될수도 있음

제한된 사용자가 sudo 명령을 사용하여 제한된 관리자의 SELinux 역할을 확보해야함

sudo 명령은 신뢰할수 있는 사용자에게 관리자의 권한을 부여, 사용자가 sudo 명령을 실행할 경우  사용자의 암호를 요구

사용자가 인증되고 명령이 허용되면 관리자 명령은 root 사용자 인것처럼 실행


SELinux 권한표 에서 보면 staff_u 및 sysadm_u 의 제한이 있는 SELinux 사용자만 기본적으로 sudo 를 사용할수 있도록 되어 있음

해당 사용자가 sudo를 사용하여 명령을 실행하면 사용자의 역할은 /etc/sudoers 설정 파일, /etc/sudoers.d/ 디렉토리의 각 파일에 따라 변경


ㅁ Configuring the sudo Transition


sudo 설정, SELinux_user_r 을 administrator_r 관리자로전환하는 방법을 설명

기존 SELinux 사용자에게 제한된관리자의 역할을 설정하려면 처음 두단계는 생략, 다음 명령은 root 사용자로 실행해야 한다는점은 유의


신규 SELinux 사용자 생성, 해당 사용자에 대해 기본 SELinux 역활 및 부수적인 제한이 있는 관리자 역할을 지정


~]# semanage user -a -r s0-s0:c0.c1023 -R "default_role_r administrator_r" SELinux_user_u

confined_u SELinux 기본역할, staff_r 에서 제한된 관리자 역할은 webadm_r


~]# semanage user -a -r s0-s0:c0.c1023 -R "staff_r webadm_r" confined_u

기본 SELinux 정책 컨텍스트 파일을 설치, 예를 들면 staff_u SELinux 사용자와동일한 SELinux 규칙을 준비하려면 staff_u 컨텍스트 파일을 복사


~]# cp /etc/selinux/targeted/contexts/users/staff_u /etc/selinux/targeted/contexts/users/SELinux_user

신규Linux 사용자를 기존의 Linux 사용자에 매핑

~]# semanage login -a -s SELinux_user_u -rs0:c0.c1023 linux_user

/etc/sudoers.d/ 디렉토리에 있는 리눅스 사용자와 동일한 이름으로 새구성파일을 생성, 다음 문자열을 추가


~]# echo "linux_user ALL=(ALL) TYPE=administaror_t ROLE=administrator_r /bin/sh " > /etc/sudoers.d/linux_user

restorecon 을 이용해서 linux_user 홈 디렉토리의 레이블을 이동


~]# restorecon -R -v /home/linux_user

시스탬 reboot


~]# systemctl reboot

새로운 Linux user로 로그인 하면 사용자는 기본 SELinux 롤 레이블리 적용


~]$ id -Z
SELinux_user_u:default_role_r:default_role_t:s0:c0.c1023

sudo 를 실행하면, 사용자의 SELinux /etc/sudoers.d/linux_user 로 지정되어 있는 SELinux 역할로 변경

sudo -i 옵션을 사용하면 대화 형 쉘이 실행


~]$ sudo -i
~]# id -Z
SELinux_user_u:administrator_r:administrator_t:s0-s0:c0.c1023

첫 단계에서 지정한 confined_u SELinux 사용자의 경우는 다음과 같이 출력됨



'Security > Linux - Selinux' 카테고리의 다른 글

selinux 04  (0) 2016.08.01
selinux 01, 02  (0) 2016.06.30

+ Recent posts