본문 바로가기

리눅스-기초명령어/보안

selinux

SELinux

Security-Enhanced Linux 는 관리자가 시스템 액세스 권한을 효과적으로 제어할 수 있게

하는 시스템용 보안 아키텍처이다.

 

1. security context

SELinux 는 모든 프로세스와 객체마다 보안 컨텍스트(Security Context)이라고 부르는 정보를 부여하여 관리하고 있다.

이 정보는 접근 권한을 확인하는데 사용되고 있으며 SELinux 를 이해하기 위한 핵심 요소이며 다음 4가지 구성 요소로 이루어져 있다.

 

요소 설명
사용자(user) 시스템의 사용자와는 별도의 SELinux 사용자이며 역할이나 레벨과 연계하여 접근 권한을 관리하는데 사용.
역할(role) 하나 혹은 그 이상의 타입과 연결되어 SELinux 의 사용자의 접근을 허용할 지 결정하는데 사용
타입(type) Type Enforcement의 속성중 하나로 프로세스의 도메인이나 파일의 타입을 지정하고 이를 기반으로 접근 통제를 수행
레벨(level) 레벨은 MLS(Multi Level System)에 필요하며 강제 접근 통제보다 더 강력한 보안이 필요할 때 사용하는 기능.

 

enforcing - SELinux security policy is enforced. 강제로 한다

permissive - SELinux prints warnings instead of enforcing. 경고를 준다

disabled - No SELinux policy is loaded 비활성화

 

2. chcon

파일들과 디렉토리 들에게 보안 context를 변경하는 방법

 

옵션

옵션 설명
-t selinux에 유형을 설정한다
-u selinux에 사용자를 설정한다
-R 하부 디렉토리까지 설정한다
-v 자세한 설명을 추가한다

 

context 변경 예시)

 

systemctl 명령어로 httpd 실행

[root@rocky2 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.

 

html디렉토리 밑에 임의 index.html 생성

[root@rocky2 ~]# echo "HI, Index" > /var/www/html/index.html

 

list의 Z옵션으로 콘텍스트 확인

[root@rocky2 ~]# ls -laZ /var/www/html/
합계 4
drwxr-xr-x. 2 root root system_u:object_r:httpd_sys_content_t:s0 24  5월 11 15:51 .
drwxr-xr-x. 4 root root system_u:object_r:httpd_sys_content_t:s0 33  5월 11 15:50 ..
-rw-r--r--. 1 root root unconfined_u:object_r:etc_t:s0           10  5월 11 15:51 index.html

 

index.html 컨텍스트 admin_home t로 변경

[root@rocky2 ~]# chcon -t admin_home_t /var/www/html/index.html

 

변경 확인

[root@rocky2 ~]# ls -laZ /var/www/html/
합계 4
drwxr-xr-x. 2 root root system_u:object_r:httpd_sys_content_t:s0 24  5월 11 15:51 .
drwxr-xr-x. 4 root root system_u:object_r:httpd_sys_content_t:s0 33  5월 11 15:50 ..
-rw-r--r--. 1 root root unconfined_u:object_r:admin_home_t:s0    10  5월 11 15:51 index.html

 

변경 콘텍스트 디폴트 값으로

[root@rocky2 ~]# restorecon /var/www/html/index.html

 

디폴트 값 확인

[root@rocky2 ~]# ls -laZ /var/www/html
합계 4
drwxr-xr-x. 2 root root system_u:object_r:httpd_sys_content_t:s0     24  5월 11 15:51 .
drwxr-xr-x. 4 root root system_u:object_r:httpd_sys_content_t:s0     33  5월 11 15:50 ..
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_sys_content_t:s0 10  5월 11 15:51 index.html

 

디렉토리 포함 context변경 (-R옵션 사용)

[root@rocky2 ~]# chcon -R -t admin_home_t /var/www/html

 

변경 확인

[root@rocky2 ~]# ls -laZ /var/www/html
합계 4
drwxr-xr-x. 2 root root system_u:object_r:admin_home_t:s0        24  5월 11 15:51 .
drwxr-xr-x. 4 root root system_u:object_r:httpd_sys_content_t:s0 33  5월 11 15:50 ..
-rw-r--r--. 1 root root unconfined_u:object_r:admin_home_t:s0    10  5월 11 15:51 index.html

 

디폴트로 context 되 돌리기

[root@rocky2 ~]# restorecon -R /var/www/html

 

확인

[root@rocky2 ~]# ls -laZ /var/www/html
합계 4
drwxr-xr-x. 2 root root system_u:object_r:httpd_sys_content_t:s0     24  5월 11 15:51 .
drwxr-xr-x. 4 root root system_u:object_r:httpd_sys_content_t:s0     33  5월 11 15:50 ..
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_sys_content_t:s0 10  5월 11 15:51 index.html






3. semanage

SELinux 정책 및 구성을 관리하는 데 사용이된다.

 

옵션

 

옵션 설명
-l 전체를 보여준다
-port 트워크 포트를 지정하는 SELinux 포트 정의를 관리하는 데 사용된다.
-fcontext SELinux 컨텍스트를 정의하는 파일 컨텍스트를 관리하는 된데 사용된다.
-d 설정을 삭제한다
-C 수정된 목록을 확인 할 수 있다.



설정 변경하는법

[root@Linux ~]# cd /etc/selinux/
[root@Linux selinux]# pwd
-rw-r--r--. 1 root root 1187  4월 24 12:17 config

[root@Linux selinux]# vi config

 

# 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.
# See also:
# https://docs.fedoraproject.org/en-US/quick-docs/getting-started-with-selinux/#getting-started-with-selinux-selinux-states-and-modes
#
# NOTE: In earlier Fedora kernel builds, SELINUX=disabled would also
# fully disable SELinux during boot. If you need a system with SELinux
# fully disabled instead of SELinux running with no policy loaded, you
# need to pass selinux=0 to the kernel command line. You can use grubby
# to persistently set the bootloader to boot with selinux=0:
#
#    grubby --update-kernel ALL --args selinux=0 # 커널 명령어를 사용하면

#                                              완전히 selinux를 끌 수있다.
# To revert back to SELinux enabled:
#
#    grubby --update-kernel ALL --remove-args selinux
#
SELINUX=enforcing  #해당칸을 enforcing, permissive, disabled 로

                    수정하면 설정된다.
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

수정후 재부팅해야 영구적으로 적용이된다.

 

일시적으로 바꾸는법

[root@rocky1 virtual]# getenforce  # 현재 selinux상태
Enforcing
[root@rocky1 virtual]# setenforce 0 #permissive 상태로 바꾼다
[root@rocky1 virtual]# getenforce
Permissive
[root@rocky

# 이 방법은 일시적이라 재부팅을 하면 원상복귀된다.



grubby

[root@rocky1 selinux]# getenforce
Disabled
[root@rocky1 selinux]# cat /proc/cmdline
BOOT_IMAGE=(hd0,msdos1)/vmlinuz-5.14.0-162.6.1.el9_1.0.1.x86_64 root=/dev/mapper/rl-roo정t ro crashkernel=1G-4G:192M,4G-64G:256M,64G-:512M resume=/dev/mapper/rl-swap rd.lvm.lv=rl/root rd.lvm.lv=rl/swap rhgb quiet selinux=0

#설정을 하고 리부트를 해야 적용이 된다.

 

semange

설정 추가 하기

[root@rocky1 QWE]# semanage fcontext -a -t httpd_sys_content_t '/QWE(/.*)?' #QWE 디렉토리에 context를 추가한다

[root@rocky1 QWE]# restorecon -Rvv /QWE # 재설정
Relabeled /QWE from unconfined_u:object_r:default_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0
Relabeled /QWE/index.html from unconfined_u:object_r:default_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0

[root@rocky1 QWE]# ls -aZl # 확인
total 8
drwxr-xr-x.  2 root root unconfined_u:object_r:httpd_sys_content_t:s0   24 May 11 14:50 .
dr-xr-xr-x. 20 root root system_u:object_r:root_t:s0                  4096 May 11 14:46 ..
-rw-r--r--.  1 root root unconfined_u:object_r:httpd_sys_content_t:s0   10 May 11 14:50 index.htm

 

삭제하기

[root@rocky1 QWE]# ls -aZl
total 8
drwxr-xr-x.  2 root root unconfined_u:object_r:default_t:s0             24 May 11 14:50 .
dr-xr-xr-x. 20 root root system_u:object_r:root_t:s0                  4096 May 11 14:46 ..
-rw-r--r--.  1 root root unconfined_u:object_r:httpd_sys_content_t:s0   10 May 11 14:50 index.html

[root@rocky1 QWE]# semanage fcontext -d -t httpd_sys_content_t '/QWE(/.*)?' #삭제 명령

[root@rocky1 QWE]# restorecon -Rvv /QWE
Relabeled /QWE/index.html from unconfined_u:object_r:httpd_sys_content_t:s0 to unconfined_u:object_r:default_t:s0

[root@rocky1 QWE]# ls -aZl
total 8
drwxr-xr-x.  2 root root unconfined_u:object_r:default_t:s0   24 May 11 14:50 .
dr-xr-xr-x. 20 root root system_u:object_r:root_t:s0        4096 May 11 14:46 ..
-rw-r--r--.  1 root root unconfined_u:object_r:default_t:s0   10 May 11 14:50 index.html

 

4 sealert

SELinux 관련 문제를 시스템 로그 파일을 분석하고 보고하는 데 사용되는 명령줄 도구이다.

[root@rocky1 ~]# vi /var/log/messages
# 로그 파일에서 sealert로 찾아서 명령을 복사
[root@rocky1 ~]# sealert -l f1c5f275-f7e3-4e27-9d8e-c9b2f09631e2
# 로그에서 복사한 명령
SELinux is preventing /usr/sbin/httpd from read access on the file index.html.

*****  Plugin catchall (100. confidence) suggests   **************************

If you believe that httpd should be allowed read access on the index.html file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# ausearch -c 'httpd' --raw | audit2allow -M my-httpd

                                        .
                                        .






5. httpd 포트변경

 

httpd 설정 변경

[root@rocky1 ~]# vi /etc/httpd/conf/httpd.conf
# vi 편집창
...
#Listen 12.34.56.78:80
#Listen 80
Listen 82
...

httpd.conf 파일에서 httpd가 82번 포트를 읽도록 변경

 

httpd를 재시작

[root@rocky1 ~]# systemctl restart httpd
Job for httpd.service failed because the control process exited with error code.
See "systemctl status httpd.service" and "journalctl -xeu httpd.service" for details.

# SELinux가 enforcing 상태이기 때문에 httpd가 정상적으로 작동할 수 없음
[root@rocky1 ~]# setenforce 0 # SELinux를 permissive상태로 변경
[root@rocky1 ~]# systemctl restart httpd
[root@rocky1 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server

     Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor pr>
     Active: active (running) since Thu 2023-05-11 16:05:53 KST; 6s ago
...
# httpd가 정상적으로 작동

May 11 15:08:21 rocky1 systemd[1]: Starting The Apache HTTP Server...
May 11 15:08:22 rocky1 httpd[14130]: AH00558: httpd: Could not reliably determi>
May 11 15:08:22 rocky1 httpd[14130]: Server configured, listening on: port 82
May 11 15:08:22 rocky1 systemd[1]: Started The Apache HTTP Server.
# httpd 포트가 82로 변경되었다

 

SELinux 설정 포트 확인

root@rocky1 ~]# semanage port -l | grep http_port
http_port_t            tcp      80, 81, 443, 488, 8008, 8009, 8443, 9000

http는 SELinux에 의해 기본적으로 지정된 포트만 사용할 수 있다

 

semanage로 http_port_t에 82번 포트  추가하기

[root@rocky1 ~]# semanage port -a -t http_port_t -p tcp 82
[root@rocky1 ~]# semanage port -l | grep http
http_cache_port_t              tcp      8080, 8118, 8123, 10001-10010
http_cache_port_t              udp      3130
http_port_t                    tcp      82, 80, 81, 443, 488, 8008, 8009, 8443, 9000

[root@rocky1 ~]# semanage port -l -C # 변경사항만 확인 할 수있다.
SELinux Port Type              Proto    Port Number

http_port_t                    tcp      82

 

82번 포트로 접속이 가능함

[root@rocky1 ~]# curl localhost
curl: (7) Failed to connect to localhost port 80: No route to host

# 80번 포트로는 접속불가
[root@rocky1 ~]# curl localhost:82
Hi, Index




SELinux 정책관리 예제 

 

semanage boolen -l 명령어를 이용해 SELinux 정책을 찾아 on으로 변경

[root@rocky1 ~]# semanage boolean -l | grep httpd_enable_homedirs
httpd_enable_homedirs          (off  ,  off)  Allow httpd to enable homedirs
[root@rocky1 ~]# setsebool -P httpd_enable_homedirs on
[root@rocky1 ~]# semanage boolean -l -C
SELinux boolean                State  Default Description

httpd_enable_homedirs          (on   ,   on)  Allow httpd to enable homedirs

해당 정책은 웹서버가 사용자 홈 디렉토리에 접근할 수 있도록 하는 SELinux정책이다.



6. httpd의 userdir 설정 허용

[root@rocky1 ~]# vi /etc/httpd/conf.d/userdir.conf
# vi 편집기

...
#    UserDir disabled # 해당 부분을 주석처리

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    #
    UserDir public_html # 이 부분의 주석을 해제 후 public_html로 변경
</IfModule>


...
# vi편집기 종료
[root@rocky1 ~]# systemctl restart httpd # 설정을 바꿨기 때문에 재시작

 

사용자 폴더 및 index 구성

 

[root@rocky1 ~]# mkdir /home/admin/public_html 
# 사용자의 홈디렉토리에 public_html 디렉토리 생성
[root@rocky1 ~]# echo "Hi" > /home/admin/public_html/index.html

# index.html 파일생성
[root@rocky1 ~]# chmod 711 /home/admin # 사용자 디렉토리에 711권한 부여
[root@rocky1 ~]# ls -lZR /home/admin
/home/admin:
total 0
drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_user_content_t:s0 24 May 12 10:01 public_html

/home/admin/public_html:
total 4
-rw-r--r--. 1 root root unconfined_u:object_r:httpd_user_content_t:s0 3 May 12 1

# context가 자동으로 httpd_user_content로 설정된다
[root@rocky1 ~]# curl localhost/~admin/
Hi

 

'리눅스-기초명령어 > 보안' 카테고리의 다른 글

authselect  (0) 2023.09.01
PAM  (1) 2023.09.01
방화벽  (0) 2023.09.01