System & Network/Linux

[Linux] Server Command Logging

EndiYou 2024. 11. 23. 20:02

보안 및 컴플라이언스 목적으로 사용자의 명령어를 특정 포맷으로 저장하는 방법


사용자 환경 설정 파일 수정

# vim /etc/profile
function history_to_syslog {
    declare command
    remoteaddr="`who am i`"
    pwd="`pwd`"
    command=$(fc -ln -0)
    if [ "$command" != "$old_command" ]; then
    logger -p local3.notice -t bash -i ? "$USER : $remoteaddr" "|| PID=$$ || Command : $command || Directory : $pwd"
    fi
    old_command=$command
}
trap history_to_syslog DEBUG
  • function history_to_syslog { ... } :
    • Bash Shell을 이용해 사용자가 실행한 명령어를 기록하기 위해 선언한 함수
  • declare command:
    • "command" 변수 선언
    • 함수 내에서 사용자가 실행하는 명령어를 저장하기 위한 변수
  • remoteaddr="`who am i`"
    • 리눅스의 who am i 명령어로 현재 로그인한 사용자의 정보를 remoteaddr 변수에 저장
    • who am i 출력 정보: 사용자 이름, 터미널 정보, 로그인 시간
  • pwd="`pwd`"
    • 사용자가 명령어를 실행할 당시의 작업 중인 디렉토리 정보를 pwd 변수에 저장
    • 실행한 명령어가 어떤 디렉토리에서 실행되었는지를 기록하기 위해 사용
  • command=$(fc -ln -0)
    • fc Bash에서 명령어 히스토리를 관리하는 명령어
    • -ln 명령어를 목록 형식으로 지정한 후 줄 번호를 제외하여 화면에 출력하는 옵션
    • -0 가장 마지막에 실행한 명령어를 선택하는 옵션
    • 이 명령어를 통해 사용자가 방금 실행 한 명령어를 command 변수에 저장
  • if [ "$command" != "$old_command" ]; then
    • 이전에 실행한 명령어old_command와 현재 명령어command를 비교
    • 비교 결과 중복된 명령어는 기록하지 않고 다른 경우에만 다음 작업 진행
  • logger -p local3.notice -t bash -i ? "$USER : $remoteaddr" "|| PID=$$ || Command : $command || Directory : $pwd"
    • logger message를 syslog에 기록하는 명령어
    • -p local3.notice 로그의 우선순위(중요도)를 notice 수준으로 지정하고, facility를 local3로 지정
      [Linux] Syslog의 Facility와 Priority Level
    • -t bash 태그를 bash로 지정 (로그 정보 구분을 위한 설정)
    • -i Process ID 값을 기록하기 위한 옵션
    • $USER : $remoteaddr 사용자 정보와 원격 접속 정보를 기록
    • || PID=$$ PID 값 기록
    • || Command : $command 실행항 명령어 기록
    • || Directory : $pwd 명령을 실행한 디렉토리 정보 기록
  • old_command=$command
    • 다음에 실행된 명령어와 비교할 수 있도록 old_command 변수에 현재 명령어를 저장
  • trap history_to_syslog DEBUG
    • Bash의 DEBUG 트랩은 사용자가 입력한 명령어가 실행되기 직전에 호출되어
    • 사용자가 실행한 모든 명령어를 history_to_syslog 함수가 가로채어 처리

rsyslog 설정 추가

# /etc/rsyslog.conf
*.info;mail.none;authpriv.none;cron.none;local3.none; /var/log/messages

local3.notice          /var/log/cmd.log
  • *.info;mail.none;authpriv.none;cron.none;local3.none; /var/log/messages
    • local3 Facility에서 발생 시킨 로그가 /var/log/messages에 중복 저장되지 않도록 제외 설정
  • local3.notice /var/log/cmd.log
    • 로그 저장 위치를 /var/log/cmd.log 로 지정
반응형