From 9f204ec7d1809c901cb6e55bc4af6ed8dd66e9fa Mon Sep 17 00:00:00 2001 From: Vehbi Sinan Tunalioglu Date: Mon, 25 Mar 2024 22:38:34 +0800 Subject: [PATCH] feat: report authorized SSH keys found on host --- src/Lhp/Remote.hs | 14 ++++++++++++++ src/Lhp/Types.hs | 2 ++ src/scripts/ssh-keys.sh | 24 ++++++++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 src/scripts/ssh-keys.sh diff --git a/src/Lhp/Remote.hs b/src/Lhp/Remote.hs index 501dde6..3592530 100644 --- a/src/Lhp/Remote.hs +++ b/src/Lhp/Remote.hs @@ -41,6 +41,7 @@ compileReport h@Types.Host {..} = do _reportKernel <- _mkKernel _hostName kvs _reportDistribution <- _mkDistribution _hostName kvs _reportDockerContainers <- _fetchHostDockerContainers _hostName + _reportSshAuthorizedKeys <- _fetchHostSshAuthorizedKeys _hostName pure Types.Report {..} @@ -104,6 +105,19 @@ _fetchHostDockerContainers h = Right sv -> pure sv +-- | Attempts to find and return all SSH authorized keys on the remote +-- host. +_fetchHostSshAuthorizedKeys + :: MonadIO m + => MonadError LhpError m + => Z.Ssh.Destination + -> m [T.Text] +_fetchHostSshAuthorizedKeys h = + filter (not . T.null . T.strip) . T.lines . Z.Text.unsafeTextFromBL <$> prog + where + prog = _toSshError h (Z.Ssh.runScript h $(embedStringFile "src/scripts/ssh-keys.sh") ["bash"]) + + -- | Smart constructor for remote host cloud information. _mkCloud :: MonadError LhpError m diff --git a/src/Lhp/Types.hs b/src/Lhp/Types.hs index b3a3b1f..fdbf35b 100644 --- a/src/Lhp/Types.hs +++ b/src/Lhp/Types.hs @@ -50,6 +50,7 @@ data Report = Report , _reportKernel :: !Kernel , _reportDistribution :: !Distribution , _reportDockerContainers :: !(Maybe [DockerContainer]) + , _reportSshAuthorizedKeys :: ![T.Text] } deriving (Eq, Generic, Show) deriving (Aeson.FromJSON, Aeson.ToJSON) via (ADC.Autodocodec Report) @@ -68,6 +69,7 @@ instance ADC.HasCodec Report where <*> ADC.requiredField "kernel" "Kernel information." ADC..= _reportKernel <*> ADC.requiredField "distribution" "Distribution information." ADC..= _reportDistribution <*> ADC.requiredField "dockerContainers" "List of Docker containers if the host is a Docker host." ADC..= _reportDockerContainers + <*> ADC.requiredField "sshAuthorizedKeys" "List of SSH authorized keys found on host." ADC..= _reportSshAuthorizedKeys -- * Cloud Information diff --git a/src/scripts/ssh-keys.sh b/src/scripts/ssh-keys.sh new file mode 100644 index 0000000..9036aca --- /dev/null +++ b/src/scripts/ssh-keys.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env sh + +################### +# SHELL BEHAVIOUR # +################### + +# Stop on errors: +set -e + +############# +# PROCEDURE # +############# + +find \ + /etc/ssh/authorized_keys.d/* \ + $(cut -f6 -d ':' /etc/passwd | sort | uniq | xargs -I{} echo "{}/.ssh/authorized_keys") \ + $(cut -f6 -d ':' /etc/passwd | sort | uniq | xargs -I{} echo "{}/.ssh/authorized_keys2") \ + 2>/dev/null | + sort -u | + xargs -I{} cat {} | + xargs -L1 echo | + grep -vE "^#" | + sort -u | + tr -s ' '