Exploit database

GH-864acc9b2fe9928f36b2141549418ef5

realityone/cve-2026-42945-scan

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-42945

32 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
realityone/cve-2026-42945-scanRevision 176c56ddb744

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

go/main.go

Go · 10,887 bytes
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	crossplane "github.com/nginxinc/nginx-go-crossplane"
	"github.com/spf13/pflag"
)

var (
	captureRefRE = regexp.MustCompile(`\$(?:([1-9][0-9]*)|\{([1-9][0-9]*)\}|([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)\})`)
	namedCapRE   = regexp.MustCompile(`\(\?P?<([A-Za-z_][A-Za-z0-9_]*)>|\(\?'([A-Za-z_][A-Za-z0-9_]*)'`)

	terminalRewriteFlags = map[string]struct{}{
		"last":      {},
		"break":     {},
		"redirect":  {},
		"permanent": {},
	}
)

type captureState struct {
	hasPositional bool
	names         map[string]struct{}
}

type finding struct {
	filename string
	line     int
	location string
}

type options struct {
	recursive bool
	single    bool
	verbose   bool
	targets   []string
}

func fromRegex(pattern string) captureState {
	return captureState{
		hasPositional: regexHasPositionalCapture(pattern),
		names:         regexNamedCaptures(pattern),
	}
}

func regexNamedCaptures(pattern string) map[string]struct{} {
	names := map[string]struct{}{}
	for _, match := range namedCapRE.FindAllStringSubmatch(pattern, -1) {
		for _, name := range match[1:] {
			if name != "" {
				names[name] = struct{}{}
			}
		}
	}
	return names
}

func regexHasPositionalCapture(pattern string) bool {
	escaped := false
	inClass := false
	runes := []rune(pattern)

	for i, char := range runes {
		if escaped {
			escaped = false
			continue
		}
		if char == '\\' {
			escaped = true
			continue
		}
		if char == '[' {
			inClass = true
			continue
		}
		if char == ']' {
			inClass = false
			continue
		}
		if char != '(' || inClass {
			continue
		}

		if runeAt(runes, i+1) != '?' {
			return true
		}

		marker := runeAt(runes, i+2)
		if marker == '<' || marker == '\'' {
			return true
		}
		if marker == 'P' && runeAt(runes, i+3) == '<' {
			return true
		}
	}

	return false
}

func runeAt(runes []rune, index int) rune {
	if index < 0 || index >= len(runes) {
		return 0
	}
	return runes[index]
}

func hasUnescapedQuestion(value string) bool {
	escaped := false
	for _, char := range value {
		if escaped {
			escaped = false
			continue
		}
		if char == '\\' {
			escaped = true
			continue
		}
		if char == '?' {
			return true
		}
	}
	return false
}

func setUsesAvailableCapture(value string, captures captureState) bool {
	for _, match := range captureRefRE.FindAllStringSubmatch(value, -1) {
		if (match[1] != "" || match[2] != "") && captures.hasPositional {
			return true
		}

		name := match[3]
		if name == "" {
			name = match[4]
		}
		if _, ok := captures.names[name]; ok && name != "" {
			return true
		}
	}
	return false
}

func locationLabel(stmt *crossplane.Directive) string {
	if len(stmt.Args) == 0 {
		return "<unnamed>"
	}
	return strings.Join(stmt.Args, " ")
}

func locationCaptureState(args []string) captureState {
	if len(args) >= 2 && (args[0] == "~" || args[0] == "~*") {
		return fromRegex(args[1])
	}
	return captureState{names: map[string]struct{}{}}
}

func scanRewriteSequence(filename string, block crossplane.Directives, locLine int, locLabel string, captures captureState, activeRiskLine int) []finding {
	riskLine := activeRiskLine

	for _, child := range block {
		if child == nil {
			continue
		}

		switch child.Directive {
		case "rewrite":
			if len(child.Args) < 2 {
				continue
			}
			captures = fromRegex(child.Args[0])
			flagValue := ""
			if len(child.Args) >= 3 {
				flagValue = strings.ToLower(child.Args[2])
			}
			_, terminal := terminalRewriteFlags[flagValue]
			if hasUnescapedQuestion(child.Args[1]) && !terminal {
				riskLine = child.Line
			}
		case "set":
			if len(child.Args) >= 2 && riskLine != 0 && setUsesAvailableCapture(child.Args[1], captures) {
				return []finding{{filename: filename, line: locLine, location: locLabel}}
			}
		default:
			if len(child.Block) > 0 {
				nested := scanRewriteSequence(filename, child.Block, locLine, locLabel, captures, riskLine)
				if len(nested) > 0 {
					return nested
				}
			}
		}
	}

	return nil
}

func scanLocation(filename string, stmt *crossplane.Directive) []finding {
	return scanRewriteSequence(
		filename,
		stmt.Block,
		stmt.Line,
		locationLabel(stmt),
		locationCaptureState(stmt.Args),
		0,
	)
}

func scanBlocks(filename string, statements crossplane.Directives) []finding {
	var findings []finding
	for _, stmt := range statements {
		if stmt == nil {
			continue
		}
		if stmt.Directive == "location" {
			findings = append(findings, scanLocation(filename, stmt)...)
			continue
		}
		if len(stmt.Block) > 0 {
			findings = append(findings, scanBlocks(filename, stmt.Block)...)
		}
	}
	return findings
}

func scanParsedConfig(config crossplane.Config) []finding {
	filename, err := filepath.Abs(config.File)
	if err != nil {
		filename = config.File
	}
	return scanBlocks(filename, config.Parsed)
}

func hasGlobMagic(target string) bool {
	return strings.ContainsAny(target, "*?[")
}

func expandTargets(targets []string, recursive bool) ([]string, error) {
	var paths []string

	for _, target := range targets {
		var matches []string
		if hasGlobMagic(target) {
			globMatches, err := filepath.Glob(target)
			if err != nil {
				return nil, err
			}
			matches = append(matches, globMatches...)
			if recursive && !strings.Contains(target, "**") {
				dir, base := filepath.Split(target)
				dir = strings.TrimSuffix(dir, string(os.PathSeparator))
				if dir == "" {
					dir = "."
				}
				if hasGlobMagic(base) && !hasGlobMagic(dir) {
					recursiveMatches, err := recursiveGlob(dir, base)
					if err != nil {
						return nil, err
					}
					matches = append(matches, recursiveMatches...)
				}
			}
		} else {
			matches = []string{target}
		}

		for _, match := range matches {
			info, err := os.Stat(match)
			if err != nil {
				fmt.Fprintf(os.Stderr, "warning: target not found: %s\n", target)
				continue
			}

			if info.IsDir() {
				dirMatches, err := confFilesInDir(match, recursive)
				if err != nil {
					return nil, err
				}
				paths = append(paths, dirMatches...)
				continue
			}

			paths = append(paths, match)
		}
	}

	return dedupePaths(paths), nil
}

func recursiveGlob(root, basePattern string) ([]string, error) {
	var matches []string
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			return nil
		}
		ok, err := filepath.Match(basePattern, filepath.Base(path))
		if err != nil {
			return err
		}
		if ok {
			matches = append(matches, path)
		}
		return nil
	})
	return matches, err
}

func confFilesInDir(root string, recursive bool) ([]string, error) {
	if !recursive {
		return filepath.Glob(filepath.Join(root, "*.conf"))
	}

	var matches []string
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			return nil
		}
		if filepath.Ext(path) == ".conf" {
			matches = append(matches, path)
		}
		return nil
	})
	return matches, err
}

func dedupePaths(paths []string) []string {
	seen := map[string]struct{}{}
	var unique []string

	for _, path := range paths {
		key, err := filepath.Abs(path)
		if err != nil {
			key = path
		}
		if _, ok := seen[key]; ok {
			continue
		}
		seen[key] = struct{}{}
		unique = append(unique, path)
	}

	return unique
}

func parseArgs(args []string) (options, error) {
	var opts options

	flags := pflag.NewFlagSet("scan", pflag.ContinueOnError)
	help := flags.BoolP("help", "h", false, "show help")
	flags.BoolVarP(&opts.recursive, "recursive", "r", false, "recurse into directory targets when looking for *.conf files")
	flags.BoolVar(&opts.single, "single", false, "scan only the given files and do not let crossplane follow include directives")
	flags.BoolVarP(&opts.verbose, "verbose", "v", false, "print crossplane parse/include warnings to stderr")
	flags.Usage = func() {
		fmt.Fprintf(flags.Output(), "usage: scan [-h] [-r] [--single] [-v] [targets ...]\n\n")
		fmt.Fprintf(flags.Output(), "Scan nginx configs for CVE-2026-42945 rewrite/set locations.\n\n")
		flags.PrintDefaults()
	}

	if err := flags.Parse(args); err != nil {
		return opts, err
	}
	if *help {
		flags.Usage()
		return opts, pflag.ErrHelp
	}

	opts.targets = flags.Args()
	if len(opts.targets) == 0 {
		opts.targets = []string{"."}
	}

	return opts, nil
}

func run(args []string) int {
	opts, err := parseArgs(args)
	if err != nil {
		if err == pflag.ErrHelp {
			return 0
		}
		return 2
	}

	targets, err := expandTargets(opts.targets, opts.recursive)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		return 2
	}
	if len(targets) == 0 {
		fmt.Fprintln(os.Stderr, "error: no config files found")
		return 2
	}

	var findings []finding
	parsedAny := false

	for _, target := range targets {
		payload, err := crossplane.Parse(target, &crossplane.ParseOptions{
			SingleFile:                opts.single,
			SkipDirectiveContextCheck: true,
			SkipDirectiveArgsCheck:    true,
		})
		if err != nil && opts.verbose {
			fmt.Fprintf(os.Stderr, "warning: %v\n", err)
		}
		if payload == nil {
			continue
		}

		if opts.verbose {
			for _, parseErr := range payload.Errors {
				fmt.Fprintf(os.Stderr, "warning: %s\n", payloadErrorString(parseErr))
			}
		}

		for _, config := range payload.Config {
			if config.Status != "ok" && opts.verbose {
				for _, configErr := range config.Errors {
					fmt.Fprintf(os.Stderr, "warning: %s\n", configErrorString(config.File, configErr))
				}
			}
			if len(config.Parsed) == 0 {
				if opts.verbose {
					fmt.Fprintf(os.Stderr, "warning: no parsed statements in %s\n", config.File)
				}
				continue
			}

			parsedAny = true
			findings = append(findings, scanParsedConfig(config)...)
		}
	}

	findings = uniqueFindings(findings)
	for _, finding := range findings {
		fmt.Printf("%s:%d -> location %s\n", finding.filename, finding.line, finding.location)
	}

	if len(findings) > 0 {
		return 1
	}
	if !parsedAny {
		return 2
	}
	return 0
}

func payloadErrorString(err crossplane.PayloadError) string {
	if err.Line != nil {
		return fmt.Sprintf("%s:%d: %v", err.File, *err.Line, err.Error)
	}
	if err.File != "" {
		return fmt.Sprintf("%s: %v", err.File, err.Error)
	}
	return fmt.Sprint(err.Error)
}

func configErrorString(filename string, err crossplane.ConfigError) string {
	if err.Line != nil {
		return fmt.Sprintf("%s:%d: %v", filename, *err.Line, err.Error)
	}
	if filename != "" {
		return fmt.Sprintf("%s: %v", filename, err.Error)
	}
	return fmt.Sprint(err.Error)
}

func uniqueFindings(findings []finding) []finding {
	seen := map[string]struct{}{}
	var unique []finding
	for _, item := range findings {
		key := fmt.Sprintf("%s\x00%d\x00%s", item.filename, item.line, item.location)
		if _, ok := seen[key]; ok {
			continue
		}
		seen[key] = struct{}{}
		unique = append(unique, item)
	}
	return unique
}

func main() {
	os.Exit(run(os.Args[1:]))
}