홈 › 리눅스 운영 › 10 / 13

보안 기초 (ssh 강화·SELinux·감사 로그)

섹션 7진행 0 / 13

3. 코드 예제

예제 1: ssh 잠그기 순서

bash
ssh-copy-id deploy@server
ssh deploy@server 'echo ok'                          # 키로 되는지 확인
sudo sed -i 's/^#\?PermitRootLogin .*/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sshd -t && sudo systemctl reload sshd
sudo sshd -T | grep -iE 'permitrootlogin|passwordauthentication'
text
ok
permitrootlogin no
passwordauthentication no

sshd -T 가 실제 적용된 값을 보여 줍니다. 파일에 여러 번 적혀 있으면 첫 번째가 이기므로 파일이 아니라 -T 로 확인합니다.

예제 2: SELinux 거부 해결

bash
sudo ausearch -m avc -ts recent | audit2why | tail -n 5
sudo restorecon -Rv /opt/myapp
sudo semanage port -a -t http_port_t -p tcp 8081
sudo systemctl restart myapp && systemctl is-active myapp
text
type=AVC msg=audit(...): avc:  denied  { name_bind } for  pid=1234 comm="java" src=8081
    Was caused by:
    The boolean or port is not allowed ... semanage port -a -t http_port_t -p tcp 8081
active

audit2why 가 실행할 명령까지 알려 줍니다. 그 한 줄만 적용하고 SELinux 는 그대로 Enforcing 입니다.

예제 3: 점검 스크립트 — 01_security_check.sh 발췌

bash
show() { printf '\n== %s\n' "$1"; }
run() { if [ "$DRY_RUN" = 1 ]; then echo "  [check] $*"; else eval "$*" 2>/dev/null | sed 's/^/  /'; fi; }
show "1. ssh 설정: root 로그인·비밀번호 인증이 꺼져 있는가"
run "sshd -T | grep -iE 'permitrootlogin|passwordauthentication'"
show "4. SELinux 상태 (Enforcing 이어야 정상)"
run "getenforce"
show "6. 위험한 파일: 777, setuid, 소유자 없는 파일"
run "find / -xdev -type f -perm -4000 | head -n 10"
text
== 1. ssh 설정: root 로그인·비밀번호 인증이 꺼져 있는가
  [check] sshd -T | grep -iE 'permitrootlogin|passwordauthentication'
== 4. SELinux 상태 (Enforcing 이어야 정상)
  [check] getenforce

Git Bash 에서는 항목만 출력되고 리눅스에서 sudo bash 로 실행하면 결과가 들여쓰기로 나옵니다. 출력을 날짜 파일로 저장해 두면 감사 증빙이 됩니다.

예제 4: 로그인 실패 상위 IP

bash
grep 'Failed password' /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -n 3
lastb -n 3
text
     42 10.0.5.77
      3 10.0.5.12
      1 10.0.5.90
kim      ssh:notty    10.0.5.77   Thu Sep 11 09:02 - 09:02  (00:00)

한 IP 에서 42번 실패는 자동화된 시도입니다. 내부 IP 이므로 그 PC 의 담당자에게 확인하고, 반복되면 방화벽에서 막습니다.