github.com/projectdiscovery/nuclei/v2@v2.9.15/pkg/protocols/utils/utils.go (about)

     1  package utils
     2  
     3  import (
     4  	"crypto/tls"
     5  	"crypto/x509"
     6  	"net/http"
     7  	"os"
     8  	"strings"
     9  
    10  	"github.com/projectdiscovery/nuclei/v2/pkg/types"
    11  )
    12  
    13  // CleanStructFieldJSONTag cleans struct json tag field
    14  func CleanStructFieldJSONTag(tag string) string {
    15  	return strings.TrimSuffix(strings.TrimSuffix(tag, ",omitempty"), ",inline")
    16  }
    17  
    18  // AddConfiguredClientCertToRequest adds the client certificate authentication to the tls.Config object and returns it
    19  func AddConfiguredClientCertToRequest(tlsConfig *tls.Config, options *types.Options) (*tls.Config, error) {
    20  	// Build the TLS config with the client certificate if it has been configured with the appropriate options.
    21  	// Only one of the options needs to be checked since the validation checks in main.go ensure that all three
    22  	// files are set if any of the client certification configuration options are.
    23  	if len(options.ClientCertFile) > 0 {
    24  		// Load the client certificate using the PEM encoded client certificate and the private key file
    25  		cert, err := tls.LoadX509KeyPair(options.ClientCertFile, options.ClientKeyFile)
    26  		if err != nil {
    27  			return nil, err
    28  		}
    29  		tlsConfig.Certificates = []tls.Certificate{cert}
    30  
    31  		// Load the certificate authority PEM certificate into the TLS configuration
    32  		caCert, err := os.ReadFile(options.ClientCAFile)
    33  		if err != nil {
    34  			return nil, err
    35  		}
    36  		caCertPool := x509.NewCertPool()
    37  		caCertPool.AppendCertsFromPEM(caCert)
    38  		tlsConfig.RootCAs = caCertPool
    39  	}
    40  	return tlsConfig, nil
    41  }
    42  
    43  // CalculateContentLength calculates content-length of the http response
    44  func CalculateContentLength(contentLength, bodyLength int64) int64 {
    45  	if contentLength > -1 {
    46  		return contentLength
    47  	}
    48  	return bodyLength
    49  }
    50  
    51  // headersToString converts http headers to string
    52  func HeadersToString(headers http.Header) string {
    53  	builder := &strings.Builder{}
    54  
    55  	for header, values := range headers {
    56  		builder.WriteString(header)
    57  		builder.WriteString(": ")
    58  
    59  		for i, value := range values {
    60  			builder.WriteString(value)
    61  
    62  			if i != len(values)-1 {
    63  				builder.WriteRune('\n')
    64  				builder.WriteString(header)
    65  				builder.WriteString(": ")
    66  			}
    67  		}
    68  		builder.WriteRune('\n')
    69  	}
    70  	return builder.String()
    71  }