github.com/projectdiscovery/nuclei/v2@v2.9.15/pkg/protocols/common/generators/validate.go (about)

     1  package generators
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/projectdiscovery/nuclei/v2/pkg/types"
    10  	fileutil "github.com/projectdiscovery/utils/file"
    11  	folderutil "github.com/projectdiscovery/utils/folder"
    12  )
    13  
    14  // validate validates the payloads if any.
    15  func (g *PayloadGenerator) validate(payloads map[string]interface{}, templatePath string) error {
    16  	for name, payload := range payloads {
    17  		switch payloadType := payload.(type) {
    18  		case string:
    19  			// check if it's a multiline string list
    20  			if len(strings.Split(payloadType, "\n")) != 1 {
    21  				return errors.New("invalid number of lines in payload")
    22  			}
    23  
    24  			// check if it's a file and try to load it
    25  			if fileutil.FileExists(payloadType) {
    26  				continue
    27  			}
    28  
    29  			changed := false
    30  
    31  			dir, _ := filepath.Split(templatePath)
    32  			templatePathInfo, _ := folderutil.NewPathInfo(dir)
    33  			payloadPathsToProbe, _ := templatePathInfo.MeshWith(payloadType)
    34  
    35  			for _, payloadPath := range payloadPathsToProbe {
    36  				if fileutil.FileExists(payloadPath) {
    37  					payloads[name] = payloadPath
    38  					changed = true
    39  					break
    40  				}
    41  			}
    42  			if !changed {
    43  				return fmt.Errorf("the %s file for payload %s does not exist or does not contain enough elements", payloadType, name)
    44  			}
    45  		case interface{}:
    46  			loadedPayloads := types.ToStringSlice(payloadType)
    47  			if len(loadedPayloads) == 0 {
    48  				return fmt.Errorf("the payload %s does not contain enough elements", name)
    49  			}
    50  		default:
    51  			return fmt.Errorf("the payload %s has invalid type", name)
    52  		}
    53  	}
    54  	return nil
    55  }