Microsoft MVP성태의 닷넷 이야기
Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정 [링크 복사], [링크+제목 복사],
조회: 1320
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 3개 있습니다.)
Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
; https://www.sysnet.pe.kr/2/0/13862

Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
; https://www.sysnet.pe.kr/2/0/13863

Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
; https://www.sysnet.pe.kr/2/0/13864




Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정

지난 글에서,

Linux - 데몬을 위한 SELinux 보안 정책 설정
; https://www.sysnet.pe.kr/2/0/13862

systemd로 실행되는 데몬 프로세스가 unconfined_service_t 보안 문맥으로 실행된다는 점과, 추가적인 policy package를 적용해 이를 변경할 수 있다는 내용을 다뤘습니다.

물론, 저렇게 하면 우리가 만든 데몬뿐만 아니라 unconfined_service_t 문맥 하에 실행되는 모든 프로세스들에 영향을 주게 되는데요, 이번 글에서는 특정 프로세스만을 대상으로 보안 정책을 적용하는 방법을 알아보겠습니다.




사실 이에 대해서 도구를 이미 제공해 주고 있는데요, 가령 우리가 만든 my-test-app 프로그램에 대해 이런 식으로 보안 정책을 생성할 수 있습니다.

$ sepolicy generate --init /usr/bin/sample/my-test-app
Loaded plugins: fastestmirror
nm: /usr/bin/sample/my-test-app: no symbols
Created the following files:
/home/testusr/temp/my_test_app.te # Type Enforcement file
/home/testusr/temp/my_test_app.if # Interface file
/home/testusr/temp/my_test_app.fc # File Contexts file
/home/testusr/temp/my_test_app_selinux.spec # Spec file
/home/testusr/temp/my_test_app.sh # Setup Script

보는 바와 같이 5개의 파일이 생성되는데요, 가장 중요한 것은 te 파일입니다.

$ cat /home/testusr/temp/my_test_app.te
policy_module(my_test_app, 1.0.0)

########################################
#
# Declarations
#

type my_test_app_t;
type my_test_app_exec_t;
init_daemon_domain(my_test_app_t, my_test_app_exec_t)

permissive my_test_app_t;

########################################
#
# my_test_app local policy
#
allow my_test_app_t self:fifo_file rw_fifo_file_perms;
allow my_test_app_t self:unix_stream_socket create_stream_socket_perms;

domain_use_interactive_fds(my_test_app_t)

files_read_etc_files(my_test_app_t)

miscfiles_read_localization(my_test_app_t)

자세히는 모르겠지만, 그래도 대충 ^^ my_test_app_t 이름으로 기본적인 rw_fifo_file_perms, create_stream_socket_perms 등의 권한이 허용되는 것을 볼 수 있습니다. 그럼 지난 글에서 다룬 것처럼 te 파일을 직접 빌드해 policy package를 생성하면 되는데요, sepolicy generate ... 명령어는 이 과정을 도와주는 shell script인 my_test_app.sh 파일도 생성해 주므로 그것을 이용할 수 있습니다.

$ cat /home/testusr/temp/my_test_app.sh
#!/bin/sh -e

DIRNAME=`dirname $0`
cd $DIRNAME
USAGE="$0 [ --update ]"
if [ `id -u` != 0 ]; then
echo 'You must be root to run this script'
exit 1
fi

if [ $# -eq 1 ]; then
        if [ "$1" = "--update" ] ; then
                time=`ls -l --time-style="+%x %X" my_test_app.te | awk '{ printf "%s %s", $6, $7 }'`
                rules=`ausearch --start $time -m avc --raw -se my_test_app`
                if [ x"$rules" != "x" ] ; then
                        echo "Found avc's to update policy with"
                        echo -e "$rules" | audit2allow -R
                        echo "Do you want these changes added to policy [y/n]?"
                        read ANS
                        if [ "$ANS" = "y" -o "$ANS" = "Y" ] ; then
                                echo "Updating policy"
                                echo -e "$rules" | audit2allow -R >> my_test_app.te
                                # Fall though and rebuild policy
                        else
                                exit 0
                        fi
                else
                        echo "No new avcs found"
                        exit 0
                fi
        else
                echo -e $USAGE
                exit 1
        fi
elif [ $# -ge 2 ] ; then
        echo -e $USAGE
        exit 1
fi

echo "Building and Loading Policy"
set -x
make -f /usr/share/selinux/devel/Makefile my_test_app.pp || exit
/usr/sbin/semodule -i my_test_app.pp

# Generate a man page off the installed module
sepolicy manpage -p . -d my_test_app_t
# Fixing the file context on /usr/bin/sample/my-test-app

/sbin/restorecon -F -R -v /usr/bin/sample/my-test-app
# Generate a rpm package for the newly generated policy

pwd=$(pwd)
rpmbuild --define "_sourcedir ${pwd}" --define "_specdir ${pwd}" --define "_builddir ${pwd}" --define "_srcrpmdir ${pwd}" --define "_rpmdir ${pwd}" --define "_buildrootdir ${pwd}/.build"  -ba my_test_app_selinux.spec

위의 스크립트를 간단하게 요약하면 다음과 같습니다.

// 인자 없이 실행한 경우

1. te 파일을 빌드해 pp 파일을 생성
2. pp 파일을 SELinux 보안 정책으로 추가
3. 실행 파일에 새로운 보안 문맥 적용

// --update 인자를 주고 실행한 경우

1. te 파일의 수정 시간을 확인
2. 해당 시간 이후로 권한이 거부된 로그를 찾고, 그것을 허용하도록 변경하는 설정을 te 파일에 추가할 것인지 물어봄
3. 추가할 경우, 이후 과정은 인자 없이 실행한 경우와 동일

의도 자체를 파악해 보면, 처음엔 기본 권한으로 시작한 후 프로그램을 실행해 보고 권한이 거부된 부분이 있다면 "--update" 인자를 주고 다시 실행해 지속적으로 권한을 추가해 나가는 식입니다. 제법 편리하게 만들어 놓은 듯한데요.

실제로 shell script 실행 전과 후의 결과를 확인해 보면,

// 실행 전, 현재 사용자는 unconfined_t, 실행 파일은 unlabeled_t에 속함
$ id -Z
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

$ ls -Z /usr/bin/sample/my-test-app
-rwxrwxrwx. root root system_u:object_r:unlabeled_t:s0 /usr/bin/sample/my-test-app

// te 파일을 빌드 및 SELinux 보안 정책으로 추가한 후, 실행 파일에 새로운 보안 문맥 적용
$ sudo ./my_test_app.sh
Building and Loading Policy
+ make -f /usr/share/selinux/devel/Makefile my_test_app.pp
Compiling targeted my_test_app module
/usr/bin/checkmodule:  loading policy configuration from tmp/my_test_app.tmp
/usr/bin/checkmodule:  policy configuration loaded
/usr/bin/checkmodule:  writing binary representation (version 19) to tmp/my_test_app.mod
Creating targeted my_test_app.pp policy package
rm tmp/my_test_app.mod.fc tmp/my_test_app.mod
+ /usr/sbin/semodule -i my_test_app.pp
+ sepolicy manpage -p . -d my_test_app_t
./my_test_app_selinux.8
+ /sbin/restorecon -F -R -v /usr/bin/sample/my-test-app
/sbin/restorecon reset /usr/bin/sample/my-test-app context unconfined_u:object_r:bin_t:s0->system_u:object_r:my_test_app_exec_t:s0
++ pwd
+ pwd=/home/testusr/temp
+ rpmbuild --define '_sourcedir /home/testusr/temp' --define '_specdir /home/testusr/temp' --define '_builddir /home/testusr/temp' --define '_srcrpmdir /home/testusr/temp' --define '_rpmdir /home/testusr/temp' --define '_buildrootdir /home/testusr/temp/.build' -ba my_test_app_selinux.spec
/home/testusr/temp/my_test_app.sh: line 52: rpmbuild: command not found

// 실행 후, my_test_app_exec_t 보안 문맥으로 바뀐 my-test-app 실행 파일
$ ls -Z /usr/bin/sample/my-test-app
-rwxrwxrwx. root root system_u:object_r:my_test_app_exec_t:s0 /usr/bin/sample/my-test-app

$ sudo /usr/sbin/semodule -l | grep my_test_app
my_test_app  1.0.0

이후 데몬을 실행해 보면,

// systemd에 등록된 my-test-app 데몬 실행
$ sudo systemctl start my-test-app

// 실행 프로세스의 보안 문맥이 "unconfined_service_t"가 아닌 "my_test_app_t"
$ ps -eZ | grep my-test-app
system_u:system_r:my_test_app_t:s0 18603 ? 00:00:00 my-test-app

물론, 저렇게 실행한 다음 거부된 권한이 있다면 이를 허용하기 위해 "--update" 인자를 주고 다시 실행해 보면 됩니다.

$ sudo ./my_test_app.sh --update




그런데, 실제로 저 과정을 해보면 좀 이상한 점이 있습니다.

예를 들어, 맨 처음 sepolicy generate ...로 생성한 my_test_app.te 파일에는 bpf에 대한 map_create 권한 허용이 없는데요, 그런데도 my-test-app을 실행해 보면 정상적으로 (rlimit.RemoveMemlock 호출에 대해) 동작합니다.

더욱 재미있는 건, 그 동작을 정상적으로 실행하는데도 불구하고 SELinux Audit 로그에는 거부된 권한 로그가 남아 있다는 점입니다. 그래서, ausearch + audit2allow로 필요한 권한을 추출하면 다음과 같은 식으로 나옵니다.

$ ls -l --time-style="+%x %X" my_test_app.te | awk '{ printf "%s %s", $6, $7 }'
01/10/2025 01:51:57

$ sudo ausearch --start 01/10/2025 01:51:57 -m avc --raw -se my_test_app | audit2allow -R

require {
        type my_test_app_t;
        type bin_t;
        class icmp_socket create;
        class bpf map_create;
        class process setrlimit;
        class capability sys_resource;
        class tcp_socket { connect create getattr getopt setopt };
        class file { execute execute_no_trans write };
        class udp_socket { connect create getattr setopt };
}

#============= my_test_app_t ==============

#!!!! WARNING: 'bin_t' is a base type.
allow my_test_app_t bin_t:file { execute execute_no_trans write };
allow my_test_app_t self:bpf map_create;
allow my_test_app_t self:capability sys_resource;
allow my_test_app_t self:icmp_socket create;
allow my_test_app_t self:process setrlimit;
allow my_test_app_t self:tcp_socket { connect create getattr getopt setopt };
allow my_test_app_t self:udp_socket { connect create getattr setopt };
auth_read_passwd(my_test_app_t)
corenet_tcp_connect_xserver_port(my_test_app_t)
dev_read_sysfs(my_test_app_t)
kernel_read_system_state(my_test_app_t)
sysnet_read_config(my_test_app_t)

그래도 어쨌든 찜찜하니 ^^ 저 내용을 반영한 te 파일로부터 정책 패키지 파일을 다시 생성하는 것이 좋을 것입니다.

$ sudo ausearch --start 01/10/2025 01:51:57 -m avc --raw -se my_test_app | audit2allow -R >> my_test_app.te

$ sudo make -f /usr/share/selinux/devel/Makefile my_test_app.pp
Compiling targeted my_test_app module
/usr/bin/checkmodule:  loading policy configuration from tmp/my_test_app.tmp
/usr/bin/checkmodule:  policy configuration loaded
/usr/bin/checkmodule:  writing binary representation (version 19) to tmp/my_test_app.mod
Creating targeted my_test_app.pp policy package
rm tmp/my_test_app.mod.fc tmp/my_test_app.mod

$ sudo /usr/sbin/semodule -i my_test_app.pp

자, 그럼 다시 데몬을 실행하고 audit 로그를 통해 필요한 권한 목록을 확인해 보면 어떨까요?

$ sudo ausearch --start 01/10/2025 02:14:56 -m avc --raw -c my_test_app | audit2allow -R
require {
        type unlabeled_t;
        type my_test_app_t;
        type bin_t;
        type unconfined_service_t;
        class icmp_socket create;
        class bpf map_create;
        class process setrlimit;
        class capability sys_resource;
        class tcp_socket { connect create getattr getopt setopt write };
        class file { execute execute_no_trans write };
        class udp_socket { connect create getattr setopt };
}

#============= my_test_app_t ==============

#!!!! This avc is allowed in the current policy
allow my_test_app_t bin_t:file { execute execute_no_trans write };

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:bpf map_create;

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:capability sys_resource;

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:icmp_socket create;

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:process setrlimit;

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:tcp_socket { connect create getattr getopt setopt };

#!!!! This avc is allowed in the current policy
allow my_test_app_t self:udp_socket { connect create getattr setopt };
auth_read_passwd(my_test_app_t)
corenet_tcp_connect_xserver_port(my_test_app_t)
dev_read_sysfs(my_test_app_t)
files_manage_generic_tmp_files(my_test_app_t)
ipa_filetrans_named_content(my_test_app_t)
kernel_read_system_state(my_test_app_t)
sysnet_read_config(my_test_app_t)

아마도, 위의 명령을 실행한 입장에서는 허용할 권한이 더 이상 없다면 아무런 출력이 없기를 기대할 것입니다. 혹은, 굳이 "#!!!! This avc is allowed in the current policy" 라면서 이미 허용된 권한들을 출력해 줄 필요가 있었을까 싶은데요, 저런 이유 때문에 만약 허용되지 않은 권한이 출력에 섞여 있다면 "--update" 인자를 주고 실행했을 때 묻는 "Do you want these changes added to policy [y/n]?" 질문에 쉽사리 "y"를 입력할 수 없습니다. (왜냐하면, y를 입력하면 저 내용들 모두가 te 파일에 추가되기 때문에!)

따라서, "--update" 인자를 깔끔하게 적용하려면 출력으로 나온 권한이 모두 허용되지 않은 로그였을 때만 "y"를 입력하는 것이 좋습니다.

즉, 허용된 것과 허용되지 않은 것이 섞여 있을 때는 "--udpate" 실행을 중지하고 편집기를 통해 te 파일을 직접 편집해 적용하는 식으로 진행하는 것을 권장합니다.




참고로, 데몬을 위해 적용한 보안 정책을 제거하는 방법이 좀 복잡합니다. 단순히 정책만 제거하면,

$ sudo /usr/sbin/semodule -r my_test_app

실행 파일의 보안 문맥은 기본값이었던 unconfined_service_t가 아닌, init_t로 변경돼 있습니다.

// my_test_app 보안 정책이 제거된 후에는,
$ sudo systemctl start my-test-app

// my_test_app_t는 아니지만 init_t 문맥으로 실행됨
$ ps -eZ | grep my-test-app
system_u:system_r:init_t:s0     12991 ?        00:00:00 my-test-app

$ seinfo --type=init_t
   init_t

이것을 원래대로 바꾸려면 한 번 더 restorecon을 실행해 주어야 합니다.

$ sudo /sbin/restorecon -F -R -v /usr/bin/sample/my-test-app

$ sudo systemctl start my-test-app

$ ps -eZ | grep my-test-app
system_u:system_r:unconfined_service_t:s0     12991 ?        00:00:00 my-test-app




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/14/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13883정성태2/12/2025190닷넷: 2317. C# - Memory Mapped I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13882정성태2/10/2025586스크립트: 70. 파이썬 - oracledb 패키지 연동 시 Thin / Thick 모드
13881정성태2/7/2025900닷넷: 2316. C# - Port I/O를 이용한 PCI Configuration Space 정보 열람파일 다운로드1
13880정성태2/5/2025871오류 유형: 947. sshd - Failed to start OpenSSH server daemon.
13879정성태2/5/20251108오류 유형: 946. Ubuntu - N: Updating from such a repository can't be done securely, and is therefore disabled by default.
13878정성태2/3/2025987오류 유형: 945. Windows - 최대 절전 모드 시 DRIVER_POWER_STATE_FAILURE 발생 (pacer.sys)
13877정성태1/25/20251082닷넷: 2315. C# - PCI 장치 열거 (레지스트리, SetupAPI)파일 다운로드1
13876정성태1/25/20251274닷넷: 2314. C# - ProcessStartInfo 타입의 Arguments와 ArgumentList파일 다운로드1
13875정성태1/24/20251264스크립트: 69. 파이썬 - multiprocessing 패키지의 spawn 모드로 동작하는 uvicorn의 workers
13874정성태1/24/20251212스크립트: 68. 파이썬 - multiprocessing Pool의 기본 프로세스 시작 모드(spawn, fork)
13873정성태1/23/20251107디버깅 기술: 217. WinDbg - PCI 장치 열거
13872정성태1/23/20251089오류 유형: 944. WinDbg - 원격 커널 디버깅이 연결은 되지만 Break (Ctrl + Break) 키를 눌러도 멈추지 않는 현상
13871정성태1/22/20251201Windows: 278. Windows - 윈도우를 다른 모니터 화면으로 이동시키는 단축키 (Window + Shift + 화살표)
13870정성태1/18/20251275개발 환경 구성: 741. WinDbg - 네트워크 커널 디버깅이 가능한 NIC 카드 지원 확대
13869정성태1/18/20251329개발 환경 구성: 740. WinDbg - _NT_SYMBOL_PATH 환경 변수에 설정한 경로로 심벌 파일을 다운로드하지 않는 경우
13868정성태1/17/20251233Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20251396오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20251359개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20251477오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20251427Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20251320Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20251284Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20251792Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20251741디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20251851디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...