go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/groups/etcgroups.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package groups
     5  
     6  import (
     7  	"bufio"
     8  	"io"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/rs/zerolog/log"
    13  	"go.mondoo.com/cnquery/providers/os/connection/shared"
    14  )
    15  
    16  // a good description of this file is available at:
    17  // https://www.cyberciti.biz/faq/understanding-etcgroup-file/
    18  func ParseEtcGroup(input io.Reader) ([]*Group, error) {
    19  	var groups []*Group
    20  	scanner := bufio.NewScanner(input)
    21  	for scanner.Scan() {
    22  		line := scanner.Text()
    23  
    24  		// check if line starts with #
    25  		if strings.HasPrefix(strings.TrimSpace(line), "#") {
    26  			continue
    27  		}
    28  
    29  		m := strings.Split(line, ":")
    30  		if len(m) >= 4 {
    31  			// parse gid
    32  			gid, err := strconv.ParseInt(m[2], 10, 0)
    33  			if err != nil {
    34  				log.Error().Err(err).Str("group", m[0]).Msg("could not parse gid")
    35  			}
    36  
    37  			// extract usernames
    38  			members := []string{}
    39  			if len(m[3]) > 0 {
    40  				members = strings.Split(m[3], ",")
    41  			}
    42  
    43  			// vagrant:x:1000:vagrant
    44  			groups = append(groups, &Group{
    45  				ID:      m[2],
    46  				Gid:     gid,
    47  				Name:    m[0],
    48  				Members: members,
    49  			})
    50  		} else {
    51  			log.Warn().Str("line", line).Msg("cannot parse etc group entry")
    52  		}
    53  	}
    54  
    55  	return groups, nil
    56  }
    57  
    58  type UnixGroupManager struct {
    59  	conn shared.Connection
    60  }
    61  
    62  func (s *UnixGroupManager) Name() string {
    63  	return "Unix Group Manager"
    64  }
    65  
    66  func (s *UnixGroupManager) Group(id string) (*Group, error) {
    67  	groups, err := s.List()
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	return findGroup(groups, id)
    73  }
    74  
    75  func (s *UnixGroupManager) List() ([]*Group, error) {
    76  	f, err := s.conn.FileSystem().Open("/etc/group")
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  
    81  	defer f.Close()
    82  	return ParseEtcGroup(f)
    83  }