4,537,991 th visitor since 2017.2.1 ( Today : 16962 )
Computer ???
No. 395
Name. swindler
Subject. SELinux
Main Cate. Linux
Sub Cate.
Date. 2009-07-28 13:36
Hit. 5096 (211.36.27.8)
File.
SELinux
각종 리눅스관련 트러블슈팅을 처리하다보면 공부해야할것들이 참 많다. 요즘 자주 거론되는 문제가 SELinux 관련된 문제들인데, SELinux 라면 아직 못들어본 사람이 꽤 많이 있을것이다.

SELinux의 내부적인 구현원리 같은 부분은 이 문서에 다루고자 하는 내용이 아니다. SELinux의 아키텍처나 코드에 대한 부분을 더 많이 알기위해서는 IBM의 기술문서(http://www-128.ibm.com/developerworks/kr/library/l-selinux/index.html) 을 참고하거나 NSA의 홈페이지(http://www.nsa.gov/selinux/)등를 참고하기 바란다. 필자는 단지 여러분이 시스템을 관리하면서 새롭게 만나게되는 SELinux에 관련된 문제를 이문서를 통해서 해결할수 있기를 바랄뿐이다.

작성자 : 김형채



    차례

    1. SELInux(Security-Enhanced Linux) 란? 1

    2. SELinux 정책이란 무엇인가? 1

    3. SELinux 설치여부 확인 2

    4. SELinux 기본설정 - /etc/sysconfig/selinux 4

    5. SELinux 서비스 설정 - setenforce 5

    6. SELinux 서비스 설정 - chcon 5

    7. SELinux 서비스 설정 - setsebool 5

    8. 사용중인 정책을 교체하는 방법은? 6

    9. SELinux LOG 7

    10. Audit2allow 8

    11. avc: denied 8

    12. 참고문헌 또는 URL 8

      1. SELInux(Security-Enhanced Linux) 란?


        SELinux 란 미 국가 보안국 (U.S. National Security Agency)리 오픈소스커뮤니티에 릴리즈한 Linux의 보안 강화 버전(코드 포함)으로서 리눅스 보안 모듈 구조체(Linux Security Modules(LSM) framework)를 이용하여 리눅스 커널에 의무 접근 제어(Mandatory Access Control - MAC)를 구현하는 것이다. Fedora Core3부터 기본으로 적용되기 시작하였고, 현재 대부분의 최신 리눅스 배포판에서 지원되고있다.

      SELinux에 대한 이해를 돕기위해서 DAC, MAC를 잠깐 이야기 해보자.

      표준 리눅스 보안은 Discretionary Access Control - DAC 모델을 따른다. DAC 모델에서, 파일과 자원에 대한 결정권은 오직 해당 객체(objects)의 사용자(user id)에게 있고 소유권(ownership)에 따라 이뤄진다. 각 사용자와 그 사용자에 의해 실행된 프로그램은 자기에게 할당된 객체에 대해 전적으로 자유재량권을 갖는다. 이러한 상황에서는, 악의 있는 일반 혹은 루트 사용자(예로, setuid와 setgid)가 실행시킨 결함이 있는 소프트웨어를 통해 주어진 객체로 원하는 어떠한 일을 해도 막아낼 방법이 없으며 보안 정책을 시스템 전체에 걸쳐 시행되도록 할 방법이 없다.

      반면에 SELinux하에서 MAC는 모든 주체(subjects - 사용자, 프로그램, 프로세스)와 객체(파일, 디바이스)에 대해서 국부적으로 허가(granular permissions)해 줄 수 있다. 응용프로그램에서 불필요한 부분은 제외하고 오직 필요한 기능에 대해서만 사용 권한을 안전하게 부여하는것이 가능하다.

      SELinux는 모든 주체 (사용자, 프로그램, 프로세스) 및 객체 (파일과 장치)에 각각 다른 권한을 부여할 수 있게 해줍니다. 따라서 사용자는 한 응용 프로그램에게 그 프로그램이 제대로 작동하는데 필요한 권한만 안전하게 부여할 수 있다.

        2 . SELinux 정책이란 무엇인가?


          SELinux 정책은 사용자, 프로그램, 프로세스 그리고 이들의 동작 대상인 파일과 디바이스를 포함한 시스템 전체, 즉, 모든 주체와 객체에 대한 접근 허가(access permissions)를 포함한 패키지를 이야기한다. 페도라에서 사용가능한 정책 패키지는 strict , targeted 두가지가 있다.

        페도라코어에서 SELinux 정책으로 strict policy 를 적용함으로 인해서 다양한 사용자들이 많은 문제점을 일으킴으로 인해서(일반사용자들이 SELinux를 사용하기 위해서는 수준높은 전문기술이 필요하다) 현재 RHEL4 에서는 보다 완화된 정책패키지 targeted poicy 가 설치시 기본으로 제공된다.

        targeted policy는 자주 문제시되는 부분들만 우선적으로 적용시키고, 나머지는 표준 리눅스 보안과 동일하게 운영되도록 적용한 정책이다.

        현재, targeted policy 에서는 dhcpd, httpd(apache.te), named, nscd, ntpd, portmap, snmpd, squid 그리고 syslogd 데몬에 대해서 관리한다. 이 데몬들에 대한 정책 파일은 /etc/selinux/targeted/src/policy/domains/program에서 찾을 수 있다.

          3 . SELinux 설치여부 확인


            SELinux 를 사용하고 있는지를 확인하는 방법은 보안문맥을 확인하는 방법으로 알 수 있다.

          파일, 사용자, 프로세스등의 문맥을 확인할 때는 -Z 라는 새 옵션을 이용해서 확인할 수 있다.




          ls -lZ /etc/selinux




          -rw-r--r-- root root system_u:object_r:selinux_config_t config
          drwxr-xr-x root root system_u:object_r:selinux_config_t targeted




          -Z옵션을 이용해서 보안문맥을 보여주는데 이 결과를 통해서 "system_u" 사용자, "object_r" 역할, "selinux_config_t" 타입을 확인할수 있다. 이런 문맥으로 SELinux의 정책에 비교해서 허용하거나 거부하게 되므로 문맥이 확인가능하다면 SELinux 를 사용중인 것이다..



          파일 이외에 프로세스와 사용자에도 각각 아래처럼 보안문맥을 확인할수 있다




          root@example# ps axZ | grep squid

          user_u:system_r:squid_t 3912 ? Ss 0:00 squid -D

          user_u:system_r:squid_t 3915 ? S 9:10 (squid) -D

          user_u:system_r:squid_t 3916 ? Ss 0:01 (unlinkd)




          root@example# id

          uid=0(root)

          gid=0(root)groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)

          context=root:system_r:unconfined_t




          RedHat 의 SELinux 패키지 경우에는 sestatus -v 라는 명령을 이용해서 현재 SELinux의 사용상태를 아래와 같이 확인할수 있다.

          [root@ns selinux]# sestatus -v

          SELinux status: enabled

          SELinuxfs mount: /selinux

          Current mode: enforcing

          Mode from config file: enforcing

          Policy version: 18

          Policy from config file:targeted




          Policy booleans:

          allow_ypbind active

          dhcpd_disable_trans inactive

          httpd_disable_trans active

          httpd_enable_cgi active

          httpd_enable_homedirs active

          httpd_ssi_exec active

          httpd_tty_comm inactive

          httpd_unified active

          mysqld_disable_trans inactive

          named_disable_trans active

          named_write_master_zonesactive

          nscd_disable_trans active

          ntpd_disable_trans inactive

          portmap_disable_trans inactive

          postgresql_disable_transinactive

          snmpd_disable_trans inactive

          squid_disable_trans inactive

          syslogd_disable_trans inactive

          winbind_disable_trans inactive

          ypbind_disable_trans inactive




          Process contexts:

          Current context: root:system_r:unconfined_t

          Init context: user_u:system_r:unconfined_t

          /sbin/mingetty user_u:system_r:unconfined_t

          /usr/sbin/sshd user_u:system_r:unconfined_t




          File contexts:

          Controlling term: root:object_r:devpts_t

          /etc/passwd root:object_r:etc_t

          /etc/shadow system_u:object_r:shadow_t

          /bin/bash system_u:object_r:shell_exec_t

          /bin/login system_u:object_r:bin_t

          /bin/sh system_u:object_r:bin_t -> system_u:object_r:shell_exec_t

          /sbin/agetty system_u:object_r:sbin_t

          /sbin/init system_u:object_r:init_exec_t

          /sbin/mingetty system_u:object_r:sbin_t

          /usr/sbin/sshd system_u:object_r:sbin_t

          /lib/libc.so.6 system_u:object_r:lib_t -> system_u:object_r:shlib_t

          /lib/ld-linux.so.2 system_u:object_r:lib_t -> system_u:object_r:ld_so_t

          [root@ns selinux]#

            4 . SELinux 기본설정 - /etc/sysconfig/selinux


              배포판마다 서비스 설정방법은 차이가 있다. 필자가 테스트한 레드햇과 페도라 배포판에서는 /etc/sysconfig/selinux 파일에서 SELinux 의 사용가능한 모드를 설정한다.




            /etc/sysconfig/selinux 파일의 내용




            # This file controls the state of SELinux on the system.

            # SELINUX= can take one of these three values:

            # enforcing - SELinux security policy is enforced.

            # permissive - SELinux prints warnings instead of enforcing.

            # disabled - SELinux is fully disabled.

            SELINUX=enforcing

            # SELINUXTYPE= type of policy in use. Possible values are:

            # targeted - Only targeted network daemons are protected.

            # strict - Full SELinux protection.

            SELINUXTYPE=targeted

            이 파일에는 두부분의 설정이 있는데 SELINUX 의 상태(enforcing, permissive, disabled)를 설정하는 부분과 활성화시킬 보안정책(strict 또는 targeted 중 하나)을 결정하는 SELINUXTYPE 이라는 부분이 있다.

            disabled ? SELinux 보안 제어를 사용하지 않으려면 disalbed 옵션을 선택한다. disalbed 설정은 보안 제어 기능을 끄고 시스템이 보안 정책을 사용하지 않도록 설정한다.

            permissive ? 이것을 선택하면 서비스 거부 메시지를 통보받을 수 있다. permissive 상태로 설정하면 자료와 프로그램에 이름을 할당한 후 로그를 기록하지만 보안 정책을 사용하지는 않는다. permissive 상태는 SELinux를 처음 접하는 경우 처음부터 이 기능을 완전히 활성화하지 않고 우선 이 정책을 사용해서 일반 시스템 작업시 어떠한 영향을 미치는지 알아보려는 경우 좋은 시작점이 될 수 있다. 그러나 경고 옵션을 선택시 가끔씩 보안경고 대상이 아닌 것을 경고 대상으로 탐지하는 오류(false positive)나 경고 대상인 것을 탐지하지 않는 오류(false negative)가 발생할 가능성도 있으니 주의가 필요하다.

            enforcing ? SELinux를 완전히 활성화하시려면 enforcing 옵션을 선택하자. enforcing 옵션을 선택하면 추가 시스템 보안을 위해 모든 보안 정책 (예, 허가가 없는 사용자가 특정한 파일이나 프로그램에 접근하는 것을 거부하기)을 사용한다. SELinux가 완전히 실행되어도 아무런 지장을 받지않고 일반적인 시스템 작업을 수행할 수 있다고 자신하시경우 이 옵션을 선택한다.

              5 . SELinux 서비스 설정 - setenforce

                SELinux의 서비스 상태를 변경해야 하는 필요가 있을때는 직접 /etc/sysconfig/selinux 파일에서 SELINUX=enforcing , 또는 SELINUX=permissive 처럼 수정해서 변경하는 방법도 있지만 setenforce 라는 명령어를 이용할수 있다.
              "setenforce 0" 이라고 명령을 내리는것은 SELINUX=permissive 와 동일한 결과이며, "setenforce 1" 은 enforcing 모드를 의미한다. 시스템에서 SELinux 를 완전히 사용하지 않으려면 /etc/sysconfig/selinux 파일에서 SELINUX=disabled 처럼 설정하거나 시스템 부팅시에 부트로더의 파라미터로 selinux=0 이라고 주고 부팅하면 된다. (grub 을 사용하는 경우라면 grub 화면에서 e 를 누르고 편집모드로 들어간뒤에 kernel 줄의 맨 뒤에 selinux=0 을 적어주고 ESC, 그리고 b 를 눌러서 부팅하면 된다..)


              sentenforce 명령은 sysadm_r 권한을 갖고 수행해야 한다; 그러기 위해, newrole 명령을 사용하거나, 아니면, su -를 사용하여 root 로 사용자 전환을 하면, 자동으로 sysadm_r 권한을 얻을 수 있다.

                6 . SELinux 서비스 설정 - chcon


                  SELinux 의 보안문맥을 변경해야 하는 경우에는 chcon 이라는 명령을 사용할수 있다.

                아파치를 사용중에 분명히 디렉토리를 생성했는데도 에러가 난다면 아래처럼 http_user_content_t 를 해당 DocumentRoot 에 적용해줌으로 해결해 줄수있다.

                chcon -R -t httpd_user_content_t /home/사용자계정/public_html

                  7 . SELinux 서비스 설정 - setsebool

                    [root@ns ~]# cat /etc/selinux/targeted/booleans
                  allow_ypbind=1

                  dhcpd_disable_trans=0

                  httpd_disable_trans=1

                  httpd_enable_cgi=1

                  httpd_enable_homedirs=1

                  httpd_ssi_exec=1

                  httpd_tty_comm=0

                  httpd_unified=1

                  mysqld_disable_trans=0

                  named_disable_trans=1

                  named_write_master_zones=1

                  nscd_disable_trans=1

                  ntpd_disable_trans=0

                  portmap_disable_trans=0

                  postgresql_disable_trans=0

                  snmpd_disable_trans=0

                  squid_disable_trans=0

                  syslogd_disable_trans=0

                  winbind_disable_trans=0

                  ypbind_disable_trans=0




                    RHEL4의 경우 전환가능한 시스템의 SELinux 설정값들을 나타내는 파일은 /etc/selinux/targeted/booleans 파일이다. 파일안의 각 항목은 system-config-securitylevel 이라는 어플리케이션이나 setsebool 이라는 명령을 이용해서 변경시킬수 있으며 setsebools 을 이용하는 경우 -P 옵션을 사용하지 않으면 설정파일은 변경되지 않고 현재의 설정만 바뀌지만 -P 옵션을 같이 사용하면 /etc/selinux/targeted/booleans 파일의 내용까지 같이 변경되어 시스템 리부팅후에도 적용된다

                      8 . 사용중인 정책을 교체하는 방법은?


                        정책 교체는 가볍게 취할 사안이 아니다.

                      연구 목적으로 시험 장비(test machine)에서 새 정책을 시도하는 이외, 생산 시스템(production system)에서는 다른 정책으로 교체하기 전에 현황을 심각하게 고려해야 한다.




                      교체 작업은 간단하다. 이는 매우 안전한 방법이지만, 우선 시험 시스템에서 일차 시도해 보는 것이 바람직하다.

                      한 가지 방법은 system-config-securitylevel을 사용하여 정책을 바꾸고 재명명(relabel)하도록 파일 시스템을 설정하는 것이다.

                      수작업 절차는 다음과 같다:

                      1. /etc/selinux/config을 편집하고 SELINUXTYPE=policyname으로 정책 유형을 바꾼다.

                      2. 재부팅하여 돌아올 수 있는 지 확인하기위해, SELINUX=permissive모드로 설정한다. 이렇게 하면, SELinux는 정확한 정책하에서 가동될 것이지만, 만일 부정확한 파일 문맥 명명(labeling)과 같은 문제가 있으면 로그인하도록 할 것이다.

                      3. sysadm_r 역할을 갖춘 root로 파일 시스템을 재명명한다(relabel):

                      id -Z

                      root:sysadm_r:sysadm_t

                      fixfiles relabel

                      옵션 -l /path/to/logfile을 사용하여 표준 출력으로 로그를 볼 수 있고, 옵션 -o /path/to/file을 사용하여 검토(checked)되거나 재명명(relabel ed)된 모든 파일 리스트를 저장할 수 있다.

                      4. 시스템을 재부팅한다. 새 정책하에서의 재시작은 모든 시스템 프로세스가 적절한 문맥에서 시작되고 정책 변경으로 인한 모든 문제가 드러나게 한다.

                      5. sestatus -v 명령으로 발효된 변경사항을 확인한다. Permissive 모드로 가동된 새 시스템에서, avc: denied 메시지를 /var/log/messages에서 확인한다. 이들은 새 정책하에 문제없이 시스템이 가동되도록 해결해야 할 문제들을 표시해 준다.

                      6. 새 정책하에서 시스템이 만족스럽게 돌아갈 때, SELINUX=enforcing 으로 바꿔 실행 권한을 부여한다. 실시간에 enforcing을 활성화 시키기 위해 재부팅하거나 setenforce 1 을 실행한다.

                        9 . SELinux LOG


                          SELinux 의 로그는 /var/log/messages 파일에 아래처럼 나타난다




                        kernel: audit(1114070701.193:0): avc: denied { read } for pid=24216

                        exe=/usr/libexec/mysqld name=mysql dev=cciss/c0d0p6 ino=16408

                        scontext=user_u:system_r:mysqld_t tcontext=root:object_r:var_lib_t

                        tclass=dir




                        이 로그는 아래와 같이 해석할수 있다.




                        - 읽기 요청이 거부되었다.
                        - PID 24216을 가진 프로세스가 read를 시도한다
                        - 해당프로세스는 /usr/libexec/mysqld 이다
                        - /dev/cciss/c0d0p6 에서 작동되고 있다
                        - inode 는 16408이다.
                        - 프로세스의 SELinux 문맥은 user_u:system_r:mysqld_t 이다.
                        - tcontext=root:object_r:var_lib_t : 이파일이 읽기를 시도하는 파일은 var_lib_t 타입의 root 소유파일이다



                        SELinux LOG 각 항목의 의미

                        audit(timestamp) -- This field states that it's an audit message from SELinux and that it was logged at timestamp time (in seconds since Jan. 1st, 1970).

                        avc -- This message was from the SELinux access vector cache. Pretty much every message you are likely to see is from this cache.

                        denied | accepted -- This field indicates whether the action was denied or accepted. You may see logs of accepted messages in some cases (like reloading the policy).

                        { read | write | unlink | ... } -- This field shows the type of action that was attempted, such as reading a file, writing, unlinking, loading policy, etc.

                        for pid= -- This is the process ID that attempted the action.


                        exe= -- This is the path to the executable that started the process.

                        name= -- This is the name of the target on which the action was attempted.

                        dev= -- This is the device on which the target file is located.

                        ino= -- This is the inode of the target of the action.

                        scontext= -- This is the process's security context. This contains user, role, and type.

                        tcontext= -- This is the security context of the target of this action, for example, the file, directory, etc.

                        tclass= -- This is the class of the target object, such as directory, file, device node, or something else.

                          10 . Audit2allow


                            정책 작성자에게 유용한 도구는 /usr/bin/audit2allow 인데 이것은 /var/log/messages의 avc 메시지를 SELinux에 의해 사용될 수 있는 규칙으로 번역해준다. 사용이 불가능하다면 policycoreutils 패키지에 속해있으므로 yum install policycoreutils 처럼 설치 가능하다.

                          audit2allow명령은 세가지 방법으로 입력을 받을 수 있다. 기본은 표준입력 (stdin)이다. -i 옵션을 사용하면 /var/log/messages 로부터 입력을 읽을 수 있고 -d옵션을 사용하면 dmesg 출력으로부터 입력을 읽을 수 있다.

                            11 . avc: denied


                              이 메시지는 현재 실행된 SELinux 정책이 그 응용프로그램의 동작을 허락하지 않기 때문이다. 이러한 일에는 여러 가지 사유가 존재한다.

                            첫째, 응용프로그램이 접근하려는 파일중 하나가 잘못 명명되어있을 수 있다. 만일 AVC 메시지가 특정 파일을 참조한다면, ls -alZ /path/to/file 을 수행하여 현재 참조하는 파일명(current label)을 조사해 보라. 만일 그것이 잘못되어 보이면, restorecon -v /path/to/file 을 시도해보라. 만일 파일과 관련된 매우 많 은 거부(denials) 상황이 존재하면, fixfiles relabel 을 수행하거나, 반복적으로 디렉토리 경로를 재명명하기 위해서 -R옵션과 함께 restorecon 을 수행하고 싶을 수 있다.

                            다른 때에는, 거부(denials) 현상은 정책에 의해 거부되도록 프로그램에 설정을 바꿔서 발생될 수 있다. 예를 들면, 만일 Apache를 8800포트로 바꾸면, 보안 정책, apache.te,도 관련하여 바꿔야 할 필요가 생긴다. 정책 작성에 관한 상세한 정보가 필요하면, 외부연결 리스트(External Link List)를 보라.

                              12 . 참고문헌 또는 URL



                                Home of the SELinux project -- http://www.nsa.gov/selinux/

                              The Un-Official SELinux FAQ -- http://www.crypt.gen.nz/selinux/faq.html

                              SELinux link zoo -- http://www.crypt.gen.nz/selinux/links.html

                              Ubuntu Linux SELinux pages -- https://www.ubuntulinux.org/wiki/SELinux

                              2005.8 Sys Admin Magazine -- http://www.samag.com/documents/s=9820/sam0508a/0508a.htm

                              NSA SELinux FAQ ? http://www.nsa.gov/selinux/info/faq.cfm

                              SELinux community page ? http://selinux.sourceforge.net/

                              UnOfficial FAQ ? http://www.crypt.gen.nz/selinux/faq.html

                              Writing SE Linux policy HOWTO ? https://sourceforge.net/docman/display_doc.php?docid=21959&group_id=21266

                              Getting Started with SE Linux HOWTO: the new SE Linux (Debian) ? https://sourceforge.net/docman/display_doc.php?docid=20372&group_id=21266


                              [바로가기 링크] : http://coolx.net/cboard/computer/395


                              Name
                              Password
                              Comment
                              Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

                                2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog