Authorized_keys의 SSH 키가 마지막으로 사용된 시기를 확인할 수 있는 방법이 있습니까?

Authorized_keys의 SSH 키가 마지막으로 사용된 시기를 확인할 수 있는 방법이 있습니까?

내 데비안 스타일 서버 중 일부의 라이센스 키가 오래된 PC 등의 키로 인해 너무 커졌습니다. 로그인에 어떤 키가 사용되었는지 알 수 있는 방법이 있나요? 나는 그것을 청소하고 싶다.
/var/log/auth를 검색했지만 실제 행운은 없습니다.

답변1

아마도 이 시점에서 배울 흥미로운 부분은 SSH 키의 "설명" 필드가 매우 유용하다는 것입니다. 기본값은 user@hostname합리적이지만 사용자가 각각 다른 목적을 가진 여러 개의 SSH 키를 만드는 것이 일반적입니다.

ssh-keygen -C "this key is for backups" -t ....
ssh-keygen -C "webmaster access for www.example.com"

더 중요한 것은 공개 SSH 키가 에 삽입될 때 ~/.ssh/authorized_keys키를 식별하기 위해 주석을 유지(또는 확장)하는 것이 좋습니다. 키에 설명이 없으면 편집할 수 있습니다. 고유한 키 주석이 없으면 SHA256 해시가 공개 키와 즉각적으로 명확한 상관 관계를 갖지 않기 때문에 하나의 키를 다른 키와 구별하기가 어렵습니다.

그래서:

  • -C "this is the comment"SSH 키 생성 시 고유 주석( ) 사용
  • Authorized_keys 파일에 키를 추가할 때 주석에 키가 속한 사람뿐만 아니라 키에 대한 액세스 권한을 부여하는 이유도 반영되어 있는지 확인하세요.

주석을 (신중하게) 편집해도 키의 무결성이 손상되지 않는다는 점을 기억하십시오. 기존 공개 키(본인 또는 다른 사람의 것)에 대한 일반 설명을 편집하여 귀하 또는 현재 목적에 더 의미 있게 만들 수 있습니다.

그런데 귀하의 질문은 흥미로운 도전인 것 같습니다. 원하는 작업을 수행하는 데 있어 주요 제한 사항은 다음과 같습니다.

  • 위에서 언급한 것처럼, 사용되었거나 사용되지 않은 키를 명확하게 참조할 수 있도록 특정 키에 대해 사람이 읽을 수 있는 설명자를 보유하세요.

  • SSH 로그는 SSH 키가 사용되는 경우에 대한 소스 문서입니다. 이러한 로그는 일반적으로 무기한 보관되지 않으므로 "최근"에 사용된 SSH 키만 알 수 있습니다. 장기간 로그를 보존하더라도 로그 파일에서 연도 항목을 사용할 수 없는 경우가 많으며 알파벳순의 월 이름을 정렬하려면 더욱 지루한 작업이 필요합니다. 이 스크립트가 사용하는 지름길은 단순히 각 로그 파일에서 특정 키가 발생하는 횟수를 계산하는 것입니다.

  • SSH 로그는 일반적으로 일반 사용자에 의해 읽기 보호되어 있으므로 sudo이를 읽으려면 액세스가 필요할 수 있습니다.

하지만 어쨌든 계속하자!

"비활성"을 확인하려는 공개 키 목록은 ~/.ssh/authorized_keys파일의 키일 가능성이 높습니다. 스크립트에는 ssh내 친구가 사용할 수 있는 형식의 파일 경로 이름이 필요합니다. 특히 ssh-keygen공개 키를 읽고 기본 키의 SHA256 해시를 추출하는 데 사용됩니다. 이는 SSH 로그인과 상호 연관시키는 데 필요한 해시입니다 /var/log/auth-log*.

$ ssh-keygen -l -f .ssh/my-laptop-id_rsa.pub 
2048 SHA256:YmiLC7LFQ+mSE3SHkXzbpFuWi0HbIpGCaIUYuR6rAiM root@my-laptop (RSA)

첫 번째 매개변수(키 길이(비트 단위))는 인용하지 않지만 두 번째 매개변수는 가장 중요한 키 SHA256 해시이고 두 번째 매개변수 외부의 모든 항목은 키 주석이며 이를 반영하는 "(RSA)"가 추가됩니다. 키에 사용되는 암호화 체계입니다. ssh-keygen -l스크립트의 주요 동맹이자 여러 키를 저장하는 데 사용되는 배열 기술입니다. 하나는 SHA256 해시용 배열이고 다른 배열은 스크립트가 호출하는 각 키의 설명 또는 "태그"입니다.

마지막으로 SHA256 해시 배열을 반복하고, 파일 grep전체에서 /var/log/auth.log*각 해시의 발생 횟수를 계산하고 , 형식화된 결과를 표시합니다.

스크립트에는 개선의 여지가 많이 남아 있지만 이를 통해 문제에 접근하는 다양한 방법과 결과를 제시하는 방법에 대한 아이디어가 촉발되기를 바랍니다.

    #!/usr/bin/env bash
    
    set -e
    
    
    sha_of_pubkeys() {
    
    # Given an ssh authorized_keys file on stdin, extract the SHA256 hash of each
    # key, and return:
    #  (sha256 hash) <space> (key comment)
    # on stdout.
    
            grep '^[^#]' |
              ssh-keygen -l -f - |
              sed -Ee 's/^[^ ]* +//'
    
    } # sha_of_pubkeys
    
    
    count_sha_in_logs() {
    
    # Pass $1 with the key hash "SHA256:xxxxx"
    # We'll return stdout with "<tab>n time(s) in filename"
    
    regex="Accepted publickey for .* ssh2: .* $1$"
    grep -wc "$regex" /var/log/auth.log* |
      grep -v ':0$' |
      awk -F: '{printf "\t%8d time(s) in %s\n", $2, $1}'
    }
    
    
    ##############################
    #
    #       M A I N
    #
    ##############################
    
    
    [[ -r "$1" ]] || {
            printf "Can't read input file: %s\n" "$1"
            exit 1
    }
    
    # We'll identify pub keys by their (unique) comment field.
    # Store them in this array, indexed in order of occurrence.
    
    key_ids=()
    
    readarray -t key_ids << EOF
    $(
      # delete the first field (the hash) from sha_of_pubkeys stdout
      sha_of_pubkeys < "$1" |
        sed -Ee 's/^[^ ]* +//'
    )
    EOF
    
    # Store the SHA256 hash of each key in this array:
    
    key_shas=()
    
    readarray -t key_shas << EOF
    $(
      # the hash is the first field from sha_of_pubkeys
      sha_of_pubkeys < "$1" |
        awk '{print $1}'
    )
    EOF
    
    # How many unique keys did we find?
    
    n_ids=$(
    printf '%s\n' "${key_ids[@]}" |
      sort |
      uniq |
      wc -l
    )
    
    if ( [[ ${#key_shas[@]} -eq ${#key_ids[@]} ]] &&
         [[ ${#key_shas[@]} -eq ${n_ids} ]] )
    then
    
            printf '%d keys found in "%s".\nHere are their comment tags and key types:\n' ${n_ids} "$1"
    
            sha_count=()
            for i in $(jot $n_ids 0)
            do
                    printf '%4d ... %s\n' $(($i+1)) "${key_ids[$i]}"
                    sha_count+=( "$(count_sha_in_logs "${key_shas[$i]}")" )
            done
            printf '\n'
    
            for i in $(jot $n_ids 0)
            do
                    if [[ -z "${sha_count[$i]}" ]]
                    then
                            s='does not appear.'
                    else
                            s="$(printf 'appears:\n%s\n' "${sha_count[$i]}")"
                    fi
                    printf 'Key %d\n        label: "%s"\n   hash:  "%s"\n   %s\n\n' $(($i+1)) "${key_ids[$i]}" "${key_shas[$i]}" "$s"
            done
    
    else
    
            printf "Every key must have a comment field.\n"
            printf "Every comment field must be unique.\n"
            exit 1
    
    fi

산출:

$ sudo ./test.sh ~/.ssh/authorized_keys 
Password:
6 keys found in "/home/jim/.ssh/authorized_keys".
Here are their comment tags and key types:
   1 ... jim@w541 (RSA)
   2 ... admin@work-imac (RSA)
   3 ... admin@other-imac (RSA)
   4 ... [email protected] (RSA)
   5 ... [email protected] (ed25519) (ED25519)
   6 ... [email protected] (RSA)

Key 1
        label: "jim@w541 (RSA)"
        hash:  "SHA256:CvsACdXgliEpeQtUriFW87vpMZEbO6V7znj/3bhmPwo"
        does not appear.

Key 2
        label: "admin@work-imac (RSA)"
        hash:  "SHA256:x9wjIdW1OpGQhQ6rGiN25Vm2Y8og7/6lajHDK8jJAM4"
        does not appear.

Key 3
        label: "admin@other-imac (RSA)"
        hash:  "SHA256:LJ1DTCnQ6UAoXhmF3+4RqEbzCwiS+rZ3P692a8c/nNE"
        does not appear.

Key 4
        label: "[email protected] (RSA)"
        hash:  "SHA256:cTQi5zMvfYegFAzffkWngraE8B1lJCagOxrS+TkwSaA"
        appears:
               4 time(s) in /var/log/auth.log.1

Key 5
        label: "[email protected] (ed25519) (ED25519)"
        hash:  "SHA256:sPvGf5/+N3OkYlS3JV53esv2ASn+GDusMSbStaHkmik"
        appears:
               1 time(s) in /var/log/auth.log

Key 6
        label: "[email protected] (RSA)"
        hash:  "SHA256:58sSa6I24R+bsRgCMJ3v2Xog1G5bP7tP9o8V8dbVtec"
        does not appear.

이러한 키의 대부분은 최근에 사용되지 않았습니다. 일일 로그 회전을 가정할 때 키 5는 오늘 한 번 사용되었고 키 4는 어제 4번 사용되었습니다 /var/log/auth-log.

sudo읽기 권한이 필요하므로 파일이 얼마나 자주 참조되는지 /var/log/auth.log*살펴볼 수도 있습니다 ./root/.ssh/authorized_keys

$ sudo ./test.sh /root/.ssh/authorized_keys
8 keys found in "/root/.ssh/authorized_keys".
Here are their comment tags and key types:
   1 ... root@backup-host (RSA)
   2 ... ansible key (RSA)
   3 ... jim@jimsdesk (RSA)
   4 ... root@w541 (RSA)
   5 ... root@thumb (RSA)
   6 ... nagios@nagios-host (RSA)
   7 ... root@mrtg-host (RSA)
   8 ... jim@w541 (RSA)

Key 1
        label: "root@backup-host (RSA)"
        hash:  "SHA256:iHsBJAi3nZt3op/kuJLQShZg+hF94gBQi8mFBTa4gLI"
        appears:
               1 time(s) in /var/log/auth.log

Key 2
        label: "ansible key (RSA)"
        hash:  "SHA256:eedHBecrrsd8ESf4Ggl8S7my/p9YIhU77cvh/GrRxNY"
        does not appear.

Key 3
        label: "jim@jimsdesk (RSA)"
        hash:  "SHA256:cTQi5zMvfYegFAzffkWngraE8B1lJCagOxrS+TkwSaA"
        appears:
               4 time(s) in /var/log/auth.log.1

Key 4
        label: "root@w541 (RSA)"
        hash:  "SHA256:YmiLC7LFQ+mSE3SHkXzbpFuWi0HbIpGCaIUYuR6rAiM"
        does not appear.

Key 5
        label: "root@thumb (RSA)"
        hash:  "SHA256:Db+9kBzpOKy1DlOGYQB60njQ4uXVHBAl1pgBQ0+E0pg"
        does not appear.

Key 6
        label: "nagios@nagios-host (RSA)"
        hash:  "SHA256:dQWTtyWfp0eRyj1/6PHTLOKGOzS0hlktfd9Rqpg6vng"
        appears:
             574 time(s) in /var/log/auth.log
            1650 time(s) in /var/log/auth.log.0
            1650 time(s) in /var/log/auth.log.1
            1650 time(s) in /var/log/auth.log.2
            1650 time(s) in /var/log/auth.log.3
            1650 time(s) in /var/log/auth.log.4
            1650 time(s) in /var/log/auth.log.5
            1650 time(s) in /var/log/auth.log.6

Key 7
        label: "root@mrtg-host (RSA)"
        hash:  "SHA256:XLH0tz28SacSrur0pAfE2TB7mU37cm2BEH9IB/D+dew"
        does not appear.

Key 8
        label: "jim@w541 (RSA)"
        hash:  "SHA256:CvsACdXgliEpeQtUriFW87vpMZEbO6V7znj/3bhmPwo"
        does not appear.

관련 정보