RHCSA9 dump-1

Purple·2025년 9월 6일

rhcsa9

목록 보기
1/3

1. change root passwd

You've forgotten the root password for ServerA.
Securely reset the root password to regain access to the system.
Remember, resetting a root password should only be done as a last resort, and strong password practices should be followed after regaining access.

answere)

  • reboot
  • 원하는 kernel version을 고르고, boot option을 수정하기 위해 e를 누른다.
  • linux로 시작하는 줄의 끝으로 가기 위해 Ctrl+e를 누른다.
  • 줄의 끝에 rd.break를 추가
  • Ctrl + x를 눌러 수정된 parameter와 함께 emergency mode로 boot
  • mount -o remount,rw /sysroot
  • chroot /sysroot
  • passwd root (주의: 강력한 비밀번호 설정 필요)
  • touch /.autorelabel
  • exit 2번(chroot와 emergency shell을 순서대로 벗어나기 위해)
    자동적으로 reboot 시작 되어짐

validation

  • 재부팅 됐을때, 로그인시 root로 로그인해보기

2. configure local yum/dnf repository

Configure a Local Yum/DNF Repository on ServerA using the RHEL-9 ISO image mounted on the /mnt directory.

answere)

  • mount가 되어있는지 확인을 하고 안되어있다면, 아래 명령어를 통해 mount 진행
  • mount -o loop RHEL-9.iso /mnt
    -o loop: 일반 파일을 블록디바이스처럼 다루는 것. mount는 원래 블록디바이스에 대해서만 명령어 사용 가능
  • mount /dev/sr0 /mnt
    보통의 경우 /dev/sr0에 이미 연결되어있으므로, 위 명령어 사용
  • cp /mnt/media.repo /etc/yum.repos.d/rhel9.repo
  • vi /etc/yum.repos.d/rhel9.repo
[BaseOS]
name=BaseOS
enabled=1
gpgcheck=0
baseurl=file:///mnt/BaseOS

[AppStream]
name=AppStream
enabled=1
gpgcheck=0
baseurl=file:///mnt/AppStream

metadata_expire=-1: metadata expiration을 disable
gpgcheck=0: gpg key verification을 스킵(나중에 활성화 필요 할 수 있음)
enabled=1: repository를 활성화
특정 사이트(example.com)를 repo로 사용하라고 하는 경우, baseurl 부분을 아래와 같이 맞춰주면 된다.
baseurl=http://example.com/BaseOS
baseurl=http://example.com/AppStream

  • dnf clean all

validation

  • dnf repolist
  • dnf list

6. timezone

On ServerA, configure the system time to the America/New_York timezone.

answere)

  • timedatectl
  • timedatectl list-timezones | grep "America/New_York"
  • timedatectl set-timezone "America/New_York"

validation

  • timedatectl

7. NTP synchronization

On ServerA, ensure NTP synchronization is configured for accurate timekeeping.

answere)

  • timedatectl
    System clock synchronized: yes 확인. 아마 no일것임
  • dnf install chrony -y
  • systemctl enable --now chronyd
  • systemctl status chronyd
  • timedatectl set-ntp true

만약 특정 ntp server를 바라보게 해야하는 경우는 아래 풀이를 따른다.

  • vi /etc/chrony.conf
server example.ntp.server.com iburst

iburst: inital burst의 줄임말로, 최초 동기화 시 많은 요청 패킷을 보내는 옵션이다.

  • systemctl restart chronyd
  • chronyc sources
    chrony 서비스 연결상태 확인

validation

  • timedatectl
    System clock synchronized: yes 인지 확인

8. create VG, LV

On ServerA, use /dev/sdb to do the following:
Create a 2GiB volume group named myvg.
Create a 500MiB logical volume named mylv inside the myvg volume group.
Format the mylv logical volume with the ext4 filesystem and mount it persistently on the /mylv directory.
Extend the ext4 filesystem on mylv by 500MiB.

answere)
fdisk

  • lsblk
    /dev/sdb 확인
  • fdisk /dev/sdb
  • n
    new partitoin
  • p
    primary partitoin
  • 1
    partition number
  • Enter
    Press Enter for the default first sector
  • +2G
    create a partition of 2GB
  • t
    chage type
  • 8e
    Linux LVM
  • w
    write and quit
  • lsblk

pvcreate

  • pvcreate /dev/sdb1
  • pvs

Create VG

  • vgcreate myvg /dev/sdb1
    man vgcreate
    -s ${extent size}: PE(Physical Extent) 크기를 지정해야 할때는, -s 옵션을 쓴다.
  • vgs

Creaeting the LV

  • lvcreate -n mylv -L 500M myvg
    man lvcreate 활용 하기
    -n: lv name
    -L: size
    -l 100%FREE: vg 백프로 활용하여 lv 생성
    -l ${extent block number}: PE(Physical Extent)갯수로 size를 지정해야 할때는 -l 옵션을 쓴다.
  • lvs

Format the LV

  • mkfs.ext4 /dev/myvg/mylv

Format validation

  • blkid /dev/myvg/mylv

Mount the LV

  • mkdir /mylv
  • vi /etc/fstab
UUID=${UUID} /mylv ext4 defaults 0 0
  • mount -a
  • lsblk

mount validation

  • df -Th

Extend the LV

  • lvextend -r -L +500M /dev/myvg/mylv
    -r: resize
    -L: size
    만약 -r 옵션을 빼먹었다면 resize2fs /dev/myvg/mylv 별도 실행

LV validation

  • lvs
  • df -Th

9. HTTP/HTTPS WEB service

Set up a basic web server on ServerA to display the message Welcome to the webserver! upon connection, while ensuring that the firewall allows HTTP/HTTPS services.

answere)
configure Apache Web server

  • dnf install httpd -y
  • systemctl enable --now httpd
  • systemctl status httpd
  • vi /var/www/html/index.html
Welcome to the webserver!
  • ls -Z /var/www/html/index.html
    올바른 SELinux context(httpd_sys_content_t)가 붙어있는지 확인
  • restorecon -Rv /var/www/html
    context가 꼬여있다면, 복구
    기본 경로인 /var/www/html은 기본적으로 fcontext가 httpd_sys_content_t로 잡혀있기 때문에, 복구만 해주어도 무방
  • semanage fcontext -m -t httpd_sys_content_t '/경로(/.*)?'
    man semanage fcontext
    modify하는 동작. add를 위해서는 -m 부분을 -a로 수정
    /: 하위 디렉토리 구분자
    .*: 모든 문자열
    ?: 앞의 그룹(/.*)이 있을수도 있고, 없을수도 있음을 의미
  • restorecon -Rv /경로
    R: Recursive
    v: verbose
  • systemctl restart httpd

Firewall to allow http/https traffic

  • firewall-cmd --list-all
  • firewall-cmd --add-service=http --permanent
  • firewall-cmd --add-service=https --permanent
  • firewall-cmd --reload
  • firewall-cmd --list-all

validation

  • ss -tnlp | grep httpd
  • curl http://localhost

10. find and copy the file

Locate and copy all files larger than 3MB within the /etc directory on ServerA to a new directory /find/3mfiles.

answere)

  • mkdir -p /find/3mfiles
  • find /etc -size +3M -exec cp '{}' /find/3mfiles/ \;
    man find

validation

  • du -sh /find/3mfiles

11. boot messages

On ServerA, ensure that boot messages are displayed, not silenced, to aid in troubleshooting.

answere)

  • vi /etc/default/grub
  • GRUB_CMDLINE_LINUX로 시작하는 줄에서, rhgb quiet만 지운다.
  • find /boot -name grub.cfg
    해당 명령어의 결과로 나오는 곳으로 grub2-mkconfig -o를 통해 업데이트
    -o: output file
  • grub2-mkconfig -o /boot/grub2/grub.cfg
    bios 기반
  • grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg
    uefi 기반

validation

  • reboot
    디테일한 boot messages가 표시되는지 확인

12. bash script

On ServerA, create a Bash script named /script.sh that outputs the second argument followed by the first argument when executed with two arguments (e.g., "test2 test1" for ./script.sh test1 test2).

answere)

  • vi /script.sh
#!/bin/bash

if [[ $# -ne 2 ]]; then
	echo "usage: $0 argument1 argument2" >&2
    exit 1
else
	echo "$2 $1"
fi

$#: 인자 수

  • chmod +x /script.sh

validation

  • /script.sh test1 test2
    아래와 같이 output이 나와야 정상
test2 test1

13. user home directory

Ensure that a file named Congrats is automatically added to the home folders of all new users created on ServerA.

answere)

  • touch /etc/skel/Congrats
    /etc/skel디렉토리는 new user home directory의 template이다.
    어떤 file이나 directory가 해당 위치에 추가되면, 이후로 생기는 user의 home directory에 추가 되게 된다.

validation

  • useradd testuser
  • ls -al /home/testuser

14. password expiration

Enforce password expiration after 90 days and a minimum length of 8 characters for all user passwords on ServerA.

answere)
password expiration

  • vi /etc/login.defs
PASS_MAX_DAYS 90

password length

  • vi /etc/security/pwquality.conf
minlen=8

validation

  • useradd testuser
  • passwd testuser
    비밀번호 설정시 8자 미만 입력하여, 거부되는지 확인
  • chage -l testuser
    비밀번호 만료일 90일인지 확인

15. create user

On ServerA, create users and groups with specific permissions for directories, ensuring file ownership is correctly set for newly created files.

  1. Users:
  • amr and biko (members of the admins group)
  • carlos and david (members of the developers group)
  1. Directories:
  • /admins: Accessible only to the owner and admins group members, owned by biko.
  • /developers: Accessible only to developers group members, owned by carlos.
  1. File Ownership Requirements:
  • New files in /admins and /developers should inherit the group ownership.
  • Only file creators should be allowed to delete their files.

answere)
create users and groups

  • groupadd admins developers
  • useradd amr biko
  • usermod -aG admins amr biko
  • useradd carlos david
  • usermod -aG developers carlos david

create and configure directories

  • mkdir /admins /developers

set ownership and permission

  • chown biko:admins /admins
  • chown carlos:developers /developers
  • chmod 770 /admins /developers
  • chmod g+s /admins /developers
    set gid 설정: 하위에 새롭게 만들어지는 파일 또는 디렉터리가 group을 inherit하도록 함
  • chmod +t /admins /developers
    sticky bit 설정: file을 만든 사람만이 delete할 수 있게 함
    공유 폴더에 자주 사용되는 설정이다.

validation

  • id amr biko
    admins 그룹에 있는지 확인
  • id carlos david
    developers 그룹에 있는지 확인
  • ls -ld /admins /developers
    아래와 같은 output 확인 필요
    sticky bit, set gid 확인

16. cron job

On ServerA, configure a cron job that writes the message Get Ready! to the system log file /var/log/messages at noon (12 PM) on weekdays only. Ensure the job is executed with appropriate permissions and logging for troubleshooting.

answere)

  • which logger
    logger 절대 경로 확인
  • crontab -e
0 12 * * 1-5 /usr/bin/logger "Get Ready!"

logger를 이용해 system log(/var/log/messages)에 message를 보낸다.

validation

  • crontab -l
  • tail -f /var/log/messages

17. tar archive

On ServerA, create a compressed tar archive file named /root/local.tgz that contains the directory /usr/local/ and its contents, ensuring appropriate permissions and verification of the archive.

answere)

  • tar -cvzf /root/local.tgz /usr/local
    man tar
    c: create
    v: verbos
    z: gzip, tgz
    f: file name 지정

validation

  • tar -tvf /root/local.tgz
    t: list

18. swap partitoin

On ServerA, create a 200MB swap partition using /dev/sdb that automatically activates at boot.

answere)
check current mem

  • swapon -s

Create partition

  • fdisk /dev/sdb
  • n
    new partitoin
  • p
    primary partition
  • Enter
    press Enter to accept the default
  • Enter 2번
    accept default first and last sectors.
  • +200M
    to set the partitino size to 200MB
  • p
    print the partition table
  • t
    change the partition type
  • 2
    select partition number 2
  • 82
    partition type to Linux swap
  • p
    review the partition table and verify
  • w
    write the changes to the disk and exit

update kernel partition

  • partprobe /dev/sdb
    kernel에게 new partition table을 알리고, reboot없이 직접적인 접근이 되도록 허용
    partprobe는 개별 파티션이 아닌, 디스크 전체를 대상으로 실행해야 함

Format the Partition as Swap

  • mkswap /dev/sdb2

Get the UUID for fstab Configuration

  • lsblk
  • blkid /dev/sdb2

/etc/fstab

  • vi /etc/fstab
UUID=${UUID} none swap defaults 0 0

none: swap으로 마운트 포인트 별도 없음

Activate the Swap Partitoin

  • swapon -a

validation

  • free -h
  • swapon -s

19. ssh passwordless

Set up an SSH passwordless root remote login from ServerA to ServerB.

answere)
On ServerB: ssh server

  • firewall-cmd --list-all
  • firewall-cmd --add-service=ssh --permanent
  • firewall-cmd --reload
  • firewall-cmd --list-all
  • dnf install -y openssh-server
  • systemctl enable --now sshd
  • vi /etc/ssh/sshd_config
PermitRootLogin yes
  • systemctl restart sshd
  • systemctl status sshd

On ServerA: ssh client

  • dnf install -y openssh-clients
  • ssh-keygen
    private key 저장 위치: ~/.ssh/id_rsa
    public key 저장 위치: ~/.ssh/id_rsa.pub
  • ssh-copy-id root@ServerB
    ssh-keygen을 했을대, 키 이름이나 저장 경로를 명시적으로 바꾸지 않았더라면, ssh-copy-id 만 입력하여도 된다.
    이때 ServerB의 root비밀번호를 입력해야 한다.

validation

  • ssh root@ServerB

20. ssh maximun number fail attempts

Set the maximum number of SSH login attempts to 2 on ServerA.

answere)
set MaxAuthTries

  • vi /etc/ssh/sshd_config
MaxAuthTries 2
  • systemctl restart sshd

validation

  • ssh testuser@ServerA
    비밀번호 2회 실패 후, Too many authentication failures 문구와 함게 실패하는지 확인

21. root container

Configure ServerA to run a container named redis managed by a rootless systemd service.
The service must be declaratively defined using Quadlet.
-> RHCSA 9.0 준비중으로 Quadlet이 아닌 podman을 사용한 풀이 예정

Requirements

  • A systemd service must be generated from a Quadlet file located at ~/.config/containers/systemd/redis.container.
  • The Quadlet file must define a container with the following properties:
    - The ContainerName must be set to redis.
    - It must be created from the docker.io/library/redis image, tagged locally as localhost/myredis.
    - Host port 6379 must be mapped to the container's port 6379.
    - A directory named redis-data in the user's home directory must be created and used as a persistent volume mounted at /data.
    - The service must be configured to restart the container automatically on failure.
  • The user's session must be configured to linger.
  • SELinux must remain in Enforcing mode. Resolve any denials by setting the appropriate persistent boolean.

answere)
podman

  • dnf install -y container-tools
  • firewall-cmd --add-port=6379/tcp --permanent
  • firewall-cmd --add-service=redis --permanent
  • firewall-cmd --reload
  • firewall-cmd --list-all
  • podman search docker.io/library/redis
  • podman pull docker.io/library/redis
  • podman images
  • podman tag docker.io/library/redis localhost/myredis
  • podman images
  • mkdir -p ~/redis-data
  • getenforce
    enforcing 확인
  • setsebool -P container_manage_cgroup on
    컨테이너가 cgroup(cpu/mem 등 리소스 제어 그룹)을 직접 관리할수 있도록 SELinux정책에서 허용하는 설정

podman run
-> podman create(컨테이너 정의) + podman start(컨테이너 시작) 조합

podman run -d 
   --name redis \
   --restart=on-failure \
   -p 6379:6379 \
   -v ~/redis-data:/data:Z \
   localhost/myredis

--name: container name
--restart: restart policy(on-failure: 비정상 종료시, 자동 재시작)
-p ${host_port}:${container_port}: port forwarding
-v ${host_dir}:${container_dir}:Z: 해당 volume을 SELinux 라벨을 설정
localhost/myredis: 사용할 container image 이름

  • podman ps

podman gernerate systemd

  • cd /etc/systemd/system
  • podman generate systemd redis --new --files --name
  • view /etc/systemd/system/container-redis.service
  • podman ps
  • podman rm -f redis
    컨테이너 중복을 막기 위해 삭제
  • systemctl daemon-reload
  • systemctl enable --now container-redis.service

validation

  • systemctl status container-redis.service
  • podman ps
  • ss -lntp | grep 6379

23. bash shell script

On ServerA, write a script named /users_shells.sh that generates a list of usernames from /etc/passwd along with their login shell.

answere)

  • vi /users_shells.sh
#!/bin/bash

cat /etc/passwd | awk -F: '{print $1 " " $7}'

validation

  • chmod +x /users_shells.sh
  • /users_shells.sh

24. nice command

What is the default nice level assigned to a process when using the nice command without specifying additional niceness parameters?

answere)

  • man nice
    default 값을 확인 == 10
  • nice level ranges: -20 (highest priority) ~ 19 (lowest priority).

25. bash shell script

On ServerA, write a robust and secure shell script named /find.sh that:

  • Accepts exactly one argument: a filename pattern to search for.
  • Counts how many regular files inside /home and its subdirectories match the given pattern.
  • Displays an error and exits if:
    - No argument is provided
    - More than one argument is provided
    - The /home directory is missing
    - The find command fails during execution
  • Handles file names with spaces or special characters correctly.
  • Prints the final output in the format:
    - Found X matching file(s) in /home and its subdirectories.

answere)

  • vi /find.sh
#!/bin/bash

if [[ $# -ne 1 ]]; then
	echo "Error: Usage: $0 <pattern>. Please provide exactly one argument." >&2
    exit 1
fi

if [[ ! -d /home ]]; then
	echo "Error: /home directory not found." >&2
    exit 1
fi

FIND_FILES=$(find /home -type f -name "$1" 2>/dev/null)
EXIT_CODE=$?
if [[ "$EXIT_CODE" -ne 0 ]]; then
	echo "Error: An error occurred during the file search." >&2
    exit 1
fi

if [[ -z "$FIND_FILES" ]]; then
    echo "Found 0 matching file(s) in /home and its subdirectories."
    exit 0
fi

declare -a FILES=()
while IFS= read -r FILE; do
	FILES+=("$FILE")
done <<< "$FIND_FILES"

COUNT=${#FILES[@]}
echo "Found $COUNT matching file(s) in /home and its subdirectories."

$#: 인자의 개수
-ne: not equal
>&2: 표준 에러로 출력하겠다는 뜻
exit 1: 스크립트를 비정상 종료
$0: 스크립트 이름

[[ -d /home ]]: home directory가 없는지 확인
[[ ! -d /home ]]: home directory가 없는지 확인
[[ -f /home ]]: home directory가 있는지 확인
[[ ! -f /home ]]: home directory가 없는지 확인
-z: is null

$1: 첫번째 인자
(): 리스트의 원소로서 사용한다는 뜻
2>/dev/null: 에러 메시지를 버림
$?: 직전에 실행한 명령어의 종료 상태

declare -a files=(): array 선언
while IFS= read -r FILE; do: 입력 한 줄을 있는 그대로(공백,탭 보존)읽어서 file 변수에 넣으라는 뜻

${#FILES[@]}: 리스트의 길이

validation

  • chmod +x /find.sh
  • /find.sh "*.sh"

26. bash script

On ServerA, create a versatile and informative shell script named /trim.sh that removes all occurrences of the vowels "a," "i," "e," "o," and "u" from each provided argument. Ensure the script is well-formatted, includes error handling, produces clear output, and follows best practices.

answere)

  • vi /trim.sh
#!/bin/bash

if [[ $# -eq 0 ]]; then
	echo "Error: Please provide one or more arguments to trim."
    exit 1
fi

while IFS= read -r arg; do
	trimmed=$(echo "$arg" | tr -d 'aeiou')
	echo "$trimmed"
done <<< "$@"

$#: 인자의 개수
exit 1: 스크립트를 비정상 종료
$(): 괄호 안의 명령어의 결과를 문자열로 치환
$@: 모든 인자들을 개별 인자로 취급

validation

  • chmod +x /trim.sh
  • /trim.sh "Hello World" "This is a test"

27. background command

Which specific character, when strategically appended to a command, initiates its execution in the background, allowing you to continue interacting with the current shell while the command runs concurrently?

answere)

  • sleep 30 &
    &: 백그라운드 명령 실행

validation

  • jobs -l
    현재 백그라운드 작업 목록 및 pid 확인

28. seq command

Predict the exact output of the following command, carefully considering the seq command's syntax and behavior:

$ seq 1 5 20

answere)

  • seq FIRST INCREMENT LAST

29. backup of MBR(Master Boot Record)

Using appropriate commands, create a backup of the Master Boot Record (MBR) located on /dev/sda of ServerA. Store the backup in /backup/mbr.img and ensure it meets the following requirements:

  • Block Size: 512 bytes
  • Number of Blocks: 1
  • Verification: Confirm the backup was created successfully

answere)

  • mkdir -p /backup
  • dd if=/dev/sda bs=512 count=1 of=/backup/mbr.img
    man dd
    dd: disk dump
    if: input file
    of: output file
    bs: block size
    count: block 갯수
    status=progress: 진행 상황 실시간 표시 옵션
  • chmod 600 /backup/mbr.img

validation

  • ls -l /backup/mbr.img

30. redirection

Identify the redirection operator that enables reading input from the current source until a specified separator string, located on a separate line without trailing spaces, is encountered.

  • date, home directory 출력 필요

answere)

  • <<
    명령에 여러 줄 입력을 직접 전달할 때 사용. 예시는 아래와 같다.
cat <<EOF
today date: $(date)
home directory: $HOME
EOF

<<EOF: 지금부터 EOF까지의 내용을 stdin으로 보내라는 뜻
$(): 괄호 안의 명령어의 결과를 문자열로 치환


31. nfs server

On ServerA, configure the system to automatically mount the home directories of users Tom and Sam from ServerB using NFS.

The home directories on ServerB are located at /home/tom and /home/sam, with user IDs 1010 and 1020, respectively. The mount should be established in the local /remote_home directory on ServerA, ensuring read and write permissions, efficient resource usage, and seamless user experience.

answere)
1. Configure ServerB as the NFS Server
install nfs services

  • dnf install -y nfs-utils
  • systemctl enable --now nfs-server rpcbind
  • systemctl status nfs-server
  • systemctl status rpcbind

firewall rules for nfs

  • firewall-cmd --add-service=nfs --permanent
  • firewall-cmd --add-service=rpc-bind --permanent
  • firewall-cmd --add-service=mountd --permanent
  • firewall-cmd --reload
  • firewall-cmd --list-all

create user Tom and Sam

  • useradd -u 1010 tom
  • useradd -u 1020 sam
    u: uid 지정 옵션
  • id tom sam

configure nfs exports

  • vi /etc/exports
/home/tom ServerA(no_root_squash,rw,sync)
/home/sam ServerA(no_root_squash,rw,sync)

rw: read, write
sync: 동기식
no_root_squash: root 사용자 권한 유지
man exports에서 옵션값들에 대해 조금은 참고할수 있다.

apply and verify exports

  • exportfs -arv
    a: all
    r: re export
    v: verbose
  • showmount -e

2. Configure Autofs on ServerA(NFS Client)

  • dnf install -y nfs-utils autofs
  • useradd -M -u 1010 tom
  • useradd -M -u 1020 sam
    -M: --no-create-home, local home directory를 만들지 않기 위한 옵션
  • vi /etc/passwd
tom:x:1010:1010::/remote_home/tom:/bin/bash
sam:x:1020:1020::/remote_home/sam:/bin/bash

configure autofs for nfs mounting

  • vi /etc/auto.master
/remote_home /etc/auto.home
  • vi /etc/auto.home
tom -fstype=nfs,rw,sync ServerB:/home/tom
sam -fstype=nfs,rw,sync ServerB:/home/sam
  • systemctl enable --now autofs
  • systemctl status autofs

Verification

  • su - tom
  • df -Th
  • su - sam
  • df -Th

32. user container

On ServerA, as user sam, create a persistent, rootless Apache HTTP web server container using the "registry.redhat.io" registry. Ensure the setup follows best practices for security and efficiency, with these specifications:

  • Container Tag: httpd-24
  • Container Name: httpd
  • Registry Credentials: Username admin, Password administrator
  • Persistent Storage: Mount ~/www-data/ on the host to /var/www/html in the container
  • Initial Content: Create an index.html file in ~/www-data/ with "Hello World!"
  • Port Mapping: Host port 8080 to container port 8080
  • Environment Variables: HTTPD_USER=test, HTTPD_PASSWORD=test
  • Systemd Management: Use systemd for container persistence and automatic startup

answere)
root

  • dnf install -y container-tools
    podman(컨테이너 관리도구)등 컨테이터 실행에 필요한 패키지를 설치
  • firewall-cmd --add-port=8080/tcp --permanent
  • firewall-cmd --reload
  • getenforce
  • setsebool -P container_manage_cgroup on
    컨테이너가 cgroup(cpu/mem 등 리소스 제어 그룹)을 직접 관리할수 있도록 SELinux정책에서 허용하는 설정
  • useradd sam && passwd sam
    컨테이너를 운영할 사용자 sam 생성
  • loginctl enable-linger sam
  • loginctl show-user sam

podman

  • ssh sam@localhost로 유저 전환
    su - sam로 전환하게 되면, systemctl 명령어 실행시, --user 옵션이 적용되지 않는다.
  • podman login registry.redhat.io -u admin -p administrator
    redhat 공식 이미지 레지스트리에 인증
  • podman search registry.redhat.io/httpd-24
  • podman pull registry.redhat.io/ubi9/httpd-24
    apache 이미지 pull
  • podman images
  • podman tag registry.redhat.io/ubi9/httpd-24 httpd-24
    tag요건 충족
  • podman images
  • mkdir ~/www-data
  • echo "Hello World!" > ~/www-data/index.html
    host 볼륨 지정및, index.html 작성

podman run
-> podman create(컨테이너 정의) + podman start조합

podman run -d \
--name httpd \
--restart=on-failure \
-p 8080:8080 \
-v ~/www-data:/var/www/html:Z \
-e HTTPD_USER=test \
-e HTTPD_PASSWORD=test \
httpd-24

--name: container name
-p ${host_port}:${container_port}: 포트 포워딩
-v ${host_dir}:${container_dir}:Z: Z는 SELinux 라벨을 부여하는 것
-e: environemt variable
httpd-24: 사용할 container image 이름

  • podman ps
  • curl 0.0.0.0:8080
    Hello World! 확인

podman gernerate systemd

  • mkdir -p ~/.config/systemd/user
  • cd ~/.config/systemd/user
  • podman generate systemd httpd --new --files --name
  • view ~/.config/systemd/user/container-httpd.service
  • podman ps
  • podman rm -f httpd
    컨테이너 중복을 막기 위해 삭제
  • systemctl --user daemon-reload
  • systemctl --user enable --now container-httpd.service

validation

  • systemctl --user status container-httpd.service
  • podman ps
  • ss -lntp | grep 8080
  • curl 0.0.0.0:8080

33. web server

On ServerA, troubleshoot a web server running on port 88 that is unable to serve content correctly. Ensure the following:

  1. Web Server Functionality: All HTML files in /var/www/html are served successfully.
  2. Non-Standard Port Usage: The web server operates on port 88.
  3. Automatic Startup: The web server starts automatically at system startup.

answere)
1) apache 설치 및 활성화 확인

  • dnf install -y httpd
  • sysetmctl enable --now httpd
  • systemctl status httpd

1) apache 포트 확인

  • vi /etc/httpd/conf/httpd.conf
Listen 88
  • systemctl restart httpd
  • ss -lntp | grep httpd

2) firewall-cmd

  • firewall-cmd --list-all
    firewall 88 포트 블록킹 여부 확인
  • firewall-cmd --permanent --add-port=88/tcp
  • firewall-cmd --reload
  • firewall-cmd --list-all

3) semanage port

  • semanage port -l | grep http
    현재 허용된 포트 확인
  • semanage port -m -t http_port_t -p tcp 88
    modify하는 동작. add를 위해서는 -m 부분을 -a로 수정
  • semanage port -l | grep http

4) semanage fcontext & restorecon

  • ls -Z /var/www/html/*
    맞는 SELinux context(httpd_sys_content_t)를 갖고있는지 확인
    연습을 위해 default_t로 변경하고 테스트
  • semanage fcontext -m -t httpd_sys_content_t '/var/www/html(/.*)?'
    modify하는 동작. add를 위해서는 -m 부분을 -a로 수정
    man semanage fcontext의 EXAMPLE에서 구문 확인 가능
    (...): 그룹
    /.*: /다음에 임의의 모든 문자(.*)
    ?: 0회 또는 1회 반복
  • restorecon -Rv /var/www/html
    보안 컨텍스트를 정책에 맞게 적용하는 명령어
    R: Recursive
    v: verbose

verification

  • systemctl restart httpd
  • systemctl status httpd
  • curl http://localhost:88

34. service

On ServerA, configure the atd service to allow access for Adam while denying access specifically for Tom. Ensure the configuration aligns with Red Hat’s best practices for security and clarity.

answere)

  • echo "adam" > /etc/at.allow
    service를 이용 가능한 user로 adam을 추가
  • echo "tom" > /etc/at.deny
    service를 이용 불가능한 user로 tom을 추가
  • systemctl restart atd
  • systemctl enable atd

verification

  • su - adam
  • at
  • su - tom
  • at
    tom으로 시도시 아래와 같은 error 발생 확인
    You do not have permission to use at.

35. grep

On ServerA, locate all lines within the /etc/passwd file that include the stringtest. Create a file named /root/test containing exact copies of these lines in their original order, excluding any empty lines.

answere)

  • grep test /etc/passwd > /root/test
    일반적인 grep 풀이
  • grep -E '^.*test.*$' /etc/passwd > /root/test
    정규식 표현 풀이
    ^: 시작
    .*: 어떤 것이든
    $: 끝

36. sudo

On ServerA, create a script named /home/XSam.sh that grants the user Sam passwordless sudo access, following security best practices and validating the configuration.

answere)

  • vi /home/XSam.sh
#!/bin/bash

echo "sam ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/sam
chmod 440 /etc/sudoers.d/sam

sudo -u sam sudo -n true
if [[ $? -eq 0 ]]; then
   echo "Success"
else
   echo "Error"
   exit 1
fi

sudo -u sam: sam 사용자로 이 다음 명령을 실행하라는 뜻
sudo -n true:sudo 동작이 가능한지 테스트용으로 흔히 쓰임
$?: 직전에 실행한 명령어의 종료 상태
0: 성공(정상 종료)
1: 실패(비정상 종료)

validation

  • chmod +x /home/XSam.sh
  • ./Xsam.sh

38. tar, bzip2

On ServerA, create a compressed archive of the /usr/local/bin/ directory using tar with bzip2 compression. Exclude Git directories, as they can be large and are unnecessary for backups. Store the archive in /home with the filename local-bin.tar.bz2. Finally, verify the contents of the archive.

answere)

  • dnf install -y bzip2
    bzip2가 안깔려있는 경우도 있어, 확인해준다.
  • tar -cvjf /home/local-bin.tar.bz2 --exclude="*/.git/*" /usr/local/bin/
    man tar
    c: create
    v: verbos
    j: bzip2
    f: file

validation

  • tar -tvf /home/local-bin.tar.bz2 | grep git
    t: list
    v: verbos
    f: file

39. /var/log/messages

On ServerA, append the message Ended on $(date) by $LOGNAME to the /var/log/messages file with root privileges, using the tag my_script for the log message. Then, verify that the message was added by using regular expressions.

answere)

  • logger -t "my_script" "Ended on $(date) by $LOGNAME"
    t: tag
    $(): 괄호 안의 명령어의 결과를 문자열로 치환

validation

  • grep "my_script" /var/log/messages

40. multi-user.target

Configure ServerA to automatically boot into the multi-user.target, ensuring a non-graphical, multi-user environment for command-line administration.

answer)

  • systemctl get-default
  • systemctl set-default multi-user.target

validation

  • systemctl get-default
  • reboot
  • ll /etc/systemd/system/default.target

41. sudoers user

On ServerA, create a new user named Samir and grant him the ability to execute commands with root privileges using sudo. Ensure clarity, conciseness, and accuracy, and consider alternative approaches.

answer)

  • useradd Samir
  • passwd Samir
  • visudo
Samir ALL=(ALL) ALL

validation

  • sudo -u Samir sudo -n true

42.ssh

As user samir, securely transfer the sensitive file /etc/hosts from ServerA to the /home/samir_dir/ directory on ServerB, ensuring confidentiality and integrity during transit. Choose a secure transfer method appropriate for Red Hat Enterprise Linux (RHEL) 9.

Note:

  • User samir must have a dedicated directory (/home/samir_dir/) on ServerB with appropriate permissions.
  • Ensure that the file transfer method adheres to best practices for secure file transfer.

answer)
ServerB

  • useradd samir
  • psaswd samir
    추후 ServerA에서 ssh-copy-id 실행시, ServerB samir의 비밀번호 필요
  • mkdir -p /home/samir_dir
  • chown samir:samir /home/samir_dir
  • chmod 700 /home/samir_dir
  • firewall-cmd --list-all
  • firewall-cmd --add-service=ssh --permanent
  • firewall-cmd --reload
  • firewall-cmd --list-all
  • dnf install -y openssh-server
  • systemctl enable --now sshd
  • systemctl status sshd

On ServerA: ssh client

  • dnf install -y openssh-clients
  • ssh-keygen
    private key 저장 위치: ~/.ssh/id_rsa
    public key 저장 위치: ~/.ssh/id_rsa.pub
  • ssh-copy-id samir@ServerB
    ssh-keygen을 했을대, 키 이름이나 저장 경로를 명시적으로 바꾸지 않았더라면, ssh-copy-id 만 입력하여도 된다.
    이때 ServerB의 root비밀번호를 입력해야 한다.

validation

  • sftp samir@ServerB
  • sftp> put /etc/hosts /home/samir_dir
  • sftp> ls /home/samir_dir
  • sftp> exit

44. SELinux

You are the administrator for two Red Hat Enterprise Linux (RHEL) 9 servers, ServerA and ServerB. ServerB runs the Apache HTTP Server and needs access to files in /var/www/html/mydirectory, but SELinux is currently blocking this access. Modify the SELinux policy on ServerB to allow Apache to access these files securely, following best practices.

Additional Considerations:
1. Ensure the modification persists after a reboot.
2. Minimize impact on other applications or directories.

answer)

  • getenforce
    SELinux가 실제로 Enforcing으로 사용중인지 확인
  • ls -Z /var/www/html/mydirectory
    httpd_sys_content_t 설정되어있는지 확인
    default_t or var_t 등의 다른 라벨이면 apache가 접근 불가능

semanage fcontext

  • semanage fcontext -m -t httpd_sys_content_t '/var/www/html/mydirectory(/.*)?'
    modify하는 동작. add를 위해서는 -m 부분을 -a로 수정
    man semanage fcontext의 EXAMPLE에서 구문 확인 가능
    (...): 그룹
    /.*: /다음에 임의의 모든 문자(.*)
    ?: 0회 또는 1회 반복

restorecon

  • restorecon -Rv /var/www/html/mydirectory
    R: Recursive
    v: verbose
  • ls -Z /var/www/html/mydirectory

validation

  • echo "hello, world!" > /var/www/html/mydirectory/test.html
  • curl http://localhost/mydirectory/test.html
profile
안녕하세요.

0개의 댓글