go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/id/platformid/linux.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package platformid
     5  
     6  import (
     7  	"io"
     8  	"strings"
     9  
    10  	"go.mondoo.com/cnquery/providers/os/connection/shared"
    11  )
    12  
    13  // LinuxIdProvider read the following files to extract the machine id
    14  // "/var/lib/dbus/machine-id" and "/etc/machine-id"
    15  // TODO: this approach is only reliable for systemd managed machines
    16  type LinuxIdProvider struct {
    17  	connection shared.Connection
    18  }
    19  
    20  func (p *LinuxIdProvider) Name() string {
    21  	return "Linux Machine ID"
    22  }
    23  
    24  func (p *LinuxIdProvider) ID() (string, error) {
    25  	content, err := p.retrieveFile("/var/lib/dbus/machine-id")
    26  	if err != nil {
    27  		content, err = p.retrieveFile("/etc/machine-id")
    28  		if err != nil {
    29  			return "", err
    30  		}
    31  	}
    32  	return strings.TrimSpace(strings.ToLower(string(content))), nil
    33  }
    34  
    35  func (p *LinuxIdProvider) retrieveFile(path string) ([]byte, error) {
    36  	f, err := p.connection.FileSystem().Open(path)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	defer f.Close()
    41  
    42  	content, err := io.ReadAll(f)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	return content, nil
    48  }