go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/id/sshhostkey/sshhostkey.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package sshhostkey 5 6 import ( 7 "os" 8 9 "github.com/cockroachdb/errors" 10 "github.com/rs/zerolog/log" 11 "go.mondoo.com/cnquery/providers-sdk/v1/inventory" 12 "go.mondoo.com/cnquery/providers/os/connection" 13 "go.mondoo.com/cnquery/providers/os/connection/shared" 14 "golang.org/x/crypto/ssh" 15 ) 16 17 func Detect(t shared.Connection, p *inventory.Platform) ([]string, error) { 18 // if we are using an ssh connection we can read the hostkey from the connection 19 if sshTransport, ok := t.(*connection.SshConnection); ok { 20 identifier, err := sshTransport.PlatformID() 21 if err != nil { 22 return nil, err 23 } 24 return []string{identifier}, nil 25 } 26 27 // if we are not at the remote system, we try to load the ssh host key from local system 28 identifiers := []string{} 29 30 paths := []string{"/etc/ssh/ssh_host_ecdsa_key.pub", "/etc/ssh/ssh_host_ed25519_key.pub", "/etc/ssh/ssh_host_rsa_key.pub"} 31 // iterate over paths and read identifier 32 for i := range paths { 33 hostKeyFilePath := paths[i] 34 data, err := os.ReadFile(hostKeyFilePath) 35 if os.IsPermission(err) { 36 log.Warn().Err(err).Str("hostkey", hostKeyFilePath).Msg("no permission to access ssh hostkey") 37 continue 38 } else if os.IsNotExist(err) { 39 continue 40 } else if err != nil { 41 return nil, errors.Wrap(err, "could not read file:"+hostKeyFilePath) 42 } 43 publicKey, _, _, _, err := ssh.ParseAuthorizedKey(data) 44 if err != nil { 45 return nil, errors.Wrap(err, "could not parse public key file:"+hostKeyFilePath) 46 } 47 48 identifiers = append(identifiers, connection.PlatformIdentifier(publicKey)) 49 } 50 51 return identifiers, nil 52 }