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

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package pam
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  )
    10  
    11  type PamLine struct {
    12  	PamType string
    13  	Control string
    14  	Module  string
    15  	Options []interface{}
    16  }
    17  
    18  func ParseLine(line string) (*PamLine, error) {
    19  	line = StripComments(line)
    20  
    21  	if line == "" {
    22  		return nil, nil
    23  	}
    24  
    25  	fields := strings.Fields(line)
    26  
    27  	options := []interface{}{}
    28  
    29  	// check if we have @include
    30  	if len(fields) == 2 && fields[0] == "@include" {
    31  		return &PamLine{
    32  			PamType: fields[0],
    33  			Control: fields[1],
    34  			Module:  "",
    35  			Options: options,
    36  		}, nil
    37  	}
    38  
    39  	if len(fields) < 3 {
    40  		return &PamLine{}, fmt.Errorf("Invalid pam entry" + line)
    41  	}
    42  
    43  	// parse modules
    44  
    45  	pamType := fields[0]
    46  	control := fields[1]
    47  	// Control can either be one word or several contained in [] brackets
    48  	if control[0] == '[' && control[len(control)-1] != ']' {
    49  		return complicatedParse(fields)
    50  	}
    51  	module := fields[2]
    52  
    53  	if len(fields) >= 3 {
    54  		for _, f := range fields[3:] {
    55  			options = append(options, f)
    56  		}
    57  	} else {
    58  		options = nil
    59  	}
    60  
    61  	pl := &PamLine{
    62  		PamType: pamType,
    63  		Control: control,
    64  		Module:  module,
    65  		Options: options,
    66  	}
    67  	return pl, nil
    68  }
    69  
    70  func complicatedParse(fields []string) (*PamLine, error) {
    71  	pamType := fields[0]
    72  	control := fields[1]
    73  	i := 2
    74  	for ; i < len(fields)-1; i++ {
    75  		str := fields[i]
    76  		control += " " + str
    77  		if str[len(str)-1:] == "]" {
    78  			break
    79  		}
    80  	}
    81  	module := fields[i+1]
    82  	options := []interface{}{}
    83  	if i+2 < len(fields) {
    84  		for _, f := range fields[i+2:] {
    85  			options = append(options, f)
    86  		}
    87  	}
    88  	pl := &PamLine{
    89  		PamType: pamType,
    90  		Control: control,
    91  		Module:  module,
    92  		Options: options,
    93  	}
    94  	return pl, nil
    95  }
    96  
    97  func StripComments(line string) string {
    98  	if idx := strings.Index(line, "#"); idx >= 0 {
    99  		line = line[0:idx]
   100  	}
   101  	line = strings.Trim(line, " \t\r")
   102  	return line
   103  }