github.com/projectdiscovery/nuclei/v2@v2.9.15/pkg/protocols/common/helpers/responsehighlighter/response_highlighter.go (about)

     1  package responsehighlighter
     2  
     3  import (
     4  	"sort"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/logrusorgru/aurora"
     9  
    10  	"github.com/projectdiscovery/nuclei/v2/pkg/operators"
    11  )
    12  
    13  var colorFunction = aurora.Green
    14  
    15  func Highlight(operatorResult *operators.Result, response string, noColor, hexDump bool) string {
    16  	result := response
    17  	if operatorResult != nil && !noColor {
    18  		for _, currentMatch := range getSortedMatches(operatorResult) {
    19  			if hexDump {
    20  				highlightedHexDump, err := toHighLightedHexDump(result, currentMatch)
    21  				if err == nil {
    22  					result = highlightedHexDump.String()
    23  				}
    24  			} else {
    25  				result = highlightASCII(currentMatch, result)
    26  			}
    27  		}
    28  	}
    29  
    30  	return result
    31  }
    32  
    33  func highlightASCII(currentMatch string, result string) string {
    34  	var coloredMatchBuilder strings.Builder
    35  	for _, char := range currentMatch {
    36  		coloredMatchBuilder.WriteString(addColor(string(char)))
    37  	}
    38  
    39  	return strings.ReplaceAll(result, currentMatch, coloredMatchBuilder.String())
    40  }
    41  
    42  func getSortedMatches(operatorResult *operators.Result) []string {
    43  	sortedMatches := make([]string, 0, len(operatorResult.Matches))
    44  	for _, matches := range operatorResult.Matches {
    45  		sortedMatches = append(sortedMatches, matches...)
    46  	}
    47  
    48  	sort.Slice(sortedMatches, func(i, j int) bool {
    49  		return len(sortedMatches[i]) > len(sortedMatches[j])
    50  	})
    51  	return sortedMatches
    52  }
    53  
    54  func CreateStatusCodeSnippet(response string, statusCode int) string {
    55  	if strings.HasPrefix(response, "HTTP/") {
    56  		strStatusCode := strconv.Itoa(statusCode)
    57  		return response[:strings.Index(response, strStatusCode)+len(strStatusCode)]
    58  	}
    59  	return ""
    60  }
    61  
    62  func addColor(value string) string {
    63  	return colorFunction(value).String()
    64  }