package audit import "strings" type commandPart struct { text string piped bool } // commandCandidates lists the strings a command pattern is matched against: each // segment, and for every pipeline of two or more segments the whole pipeline // joined with " | ", so a pattern can see both sides of "curl ... | sh". Each // pipeline is joined once, so the candidates are linear in the input; joining // every prefix made an attacker-sized pipeline quadratic in time and memory. func commandCandidates(s string) []string { var out, pipeline []string closePipeline := func() { if len(pipeline) > 1 { out = append(out, strings.Join(pipeline, " | ")) } pipeline = pipeline[:0] } for _, p := range scanCommand(s) { if !p.piped { closePipeline() } pipeline = append(pipeline, p.text) out = append(out, p.text) } closePipeline() return out } type commandScanner struct { runes []rune cur strings.Builder parts []commandPart pipedNext bool } func (c *commandScanner) flush(sep rune, nextPiped bool) { text := strings.TrimSpace(c.cur.String()) c.cur.Reset() if text != "" { c.parts = append(c.parts, commandPart{text: text, piped: c.pipedNext}) c.pipedNext = nextPiped return } if sep != '\n' { c.pipedNext = nextPiped } } func (c *commandScanner) next(i int) rune { if i+1 < len(c.runes) { return c.runes[i+1] } return 0 } func (c *commandScanner) isRedirectAmpersand(i int) bool { if i > 0 && (c.runes[i-1] == '>' || c.runes[i-1] == '<') { return true } return c.next(i) == '>' } func scanCommand(s string) []commandPart { c := &commandScanner{runes: []rune(s)} var inSingle, inDouble bool for i := 0; i < len(c.runes); i++ { r := c.runes[i] switch { case r == '\\' && !inSingle && i+1 < len(c.runes): if c.runes[i+1] == '\n' { c.cur.WriteRune(' ') } else { c.cur.WriteRune(r) c.cur.WriteRune(c.runes[i+1]) } i++ case r == '\'' && !inDouble: inSingle = !inSingle c.cur.WriteRune(r) case r == '"' && !inSingle: inDouble = !inDouble c.cur.WriteRune(r) case inSingle || inDouble: c.cur.WriteRune(r) case r == '\n' || r == ';': c.flush(r, false) case r == '&' && c.next(i) == '&': c.flush(r, false) i++ case r == '&' && c.isRedirectAmpersand(i): c.cur.WriteRune(r) case r == '&': c.flush(r, false) case r == '|' && c.next(i) == '|': c.flush(r, false) i++ case r == '|': if c.next(i) == '&' { i++ } c.flush(r, true) default: c.cur.WriteRune(r) } } c.flush('\n', false) return c.parts }