|
| 1 | +package decoders |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "regexp" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "sync" |
| 10 | + |
| 11 | + ahocorasick "github.com/BobuSumisu/aho-corasick" |
| 12 | + "github.com/go-logr/logr" |
| 13 | + "golang.org/x/exp/maps" |
| 14 | + |
| 15 | + "github.com/trufflesecurity/trufflehog/v3/pkg/context" |
| 16 | + "github.com/trufflesecurity/trufflehog/v3/pkg/pb/detectorspb" |
| 17 | + "github.com/trufflesecurity/trufflehog/v3/pkg/sources" |
| 18 | +) |
| 19 | + |
| 20 | +// HtmlEntity decodes characters that are encoded as decimal, hexadecimal, or named entities. |
| 21 | +// https://www.ee.ucl.ac.uk/~mflanaga/java/HTMLandASCIItableC1.html |
| 22 | +type HtmlEntity struct{} |
| 23 | + |
| 24 | +var ( |
| 25 | + _ Decoder = (*HtmlEntity)(nil) |
| 26 | + |
| 27 | + once sync.Once |
| 28 | + htmlTrie *ahocorasick.Trie |
| 29 | +) |
| 30 | + |
| 31 | +func init() { |
| 32 | + // Use Aho-Corasick to pre-filter potential matches. |
| 33 | + once.Do(func() { |
| 34 | + keywords := map[string]struct{}{ |
| 35 | + `&#`: {}, // decimal |
| 36 | + `&#x`: {}, // hex |
| 37 | + } |
| 38 | + for entity := range namedEntityMap { |
| 39 | + keywords[strings.ToLower(entity)] = struct{}{} |
| 40 | + } |
| 41 | + htmlTrie = ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(keywords)).Build() |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +func (d *HtmlEntity) Type() detectorspb.DecoderType { |
| 46 | + return detectorspb.DecoderType_HTML |
| 47 | +} |
| 48 | + |
| 49 | +func (d *HtmlEntity) FromChunk(ctx context.Context, chunk *sources.Chunk) *DecodableChunk { |
| 50 | + if chunk == nil || len(chunk.Data) == 0 { |
| 51 | + return nil |
| 52 | + } else if m := htmlTrie.MatchFirst(chunk.Data); m == nil { |
| 53 | + return nil |
| 54 | + } |
| 55 | + |
| 56 | + var ( |
| 57 | + logger = ctx.Logger().WithName("decoders.html") |
| 58 | + // Necessary to avoid data races. |
| 59 | + chunkData = bytes.Clone(chunk.Data) |
| 60 | + matched = false |
| 61 | + ) |
| 62 | + if namedEntityPat.Match(chunkData) { |
| 63 | + matched = true |
| 64 | + chunkData = decodeNamedEntities(logger, chunkData) |
| 65 | + } |
| 66 | + if decimalEntityPat.Match(chunkData) { |
| 67 | + matched = true |
| 68 | + chunkData = decodeHtmlDecimal(logger, chunkData) |
| 69 | + } |
| 70 | + if hexEntityPat.Match(chunkData) { |
| 71 | + matched = true |
| 72 | + chunkData = decodeHtmlHex(logger, chunkData) |
| 73 | + } |
| 74 | + |
| 75 | + if matched { |
| 76 | + return &DecodableChunk{ |
| 77 | + DecoderType: d.Type(), |
| 78 | + Chunk: &sources.Chunk{ |
| 79 | + Data: chunkData, |
| 80 | + SourceName: chunk.SourceName, |
| 81 | + SourceID: chunk.SourceID, |
| 82 | + JobID: chunk.JobID, |
| 83 | + SecretID: chunk.SecretID, |
| 84 | + SourceMetadata: chunk.SourceMetadata, |
| 85 | + SourceType: chunk.SourceType, |
| 86 | + Verify: chunk.Verify, |
| 87 | + }, |
| 88 | + } |
| 89 | + } else { |
| 90 | + return nil |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +// `A` = `A` |
| 95 | +var decimalEntityPat = regexp.MustCompile(`&#(\d{1,3});`) |
| 96 | + |
| 97 | +func decodeHtmlDecimal(logger logr.Logger, input []byte) []byte { |
| 98 | + decoded := make([]byte, 0, len(input)) |
| 99 | + lastIndex := 0 |
| 100 | + |
| 101 | + for _, match := range decimalEntityPat.FindAllSubmatchIndex(input, -1) { |
| 102 | + startIndex := match[0] |
| 103 | + endIndex := match[1] |
| 104 | + decStartIndex := match[2] |
| 105 | + decEndIndex := match[3] |
| 106 | + |
| 107 | + // Copy the part of the input until the start of the entity |
| 108 | + decoded = append(decoded, input[lastIndex:startIndex]...) |
| 109 | + |
| 110 | + num, err := strconv.Atoi(string(input[decStartIndex:decEndIndex])) |
| 111 | + if err != nil { |
| 112 | + continue |
| 113 | + } |
| 114 | + |
| 115 | + // Append the decoded byte |
| 116 | + if num < 0 || num > 255 { |
| 117 | + logger.Error(errors.New("invalid decimal byte"), "Unable to decode HTML entity", "match", input[decStartIndex:decEndIndex], "byte", num) |
| 118 | + continue |
| 119 | + } |
| 120 | + decoded = append(decoded, byte(num)) |
| 121 | + lastIndex = endIndex |
| 122 | + } |
| 123 | + |
| 124 | + // Append the remaining part of the input |
| 125 | + decoded = append(decoded, input[lastIndex:]...) |
| 126 | + |
| 127 | + return decoded |
| 128 | +} |
| 129 | + |
| 130 | +// `A` = `` |
| 131 | +var hexEntityPat = regexp.MustCompile(`(?i)&#x([a-f0-9]{1,2});`) |
| 132 | + |
| 133 | +func decodeHtmlHex(logger logr.Logger, input []byte) []byte { |
| 134 | + decoded := make([]byte, 0, len(input)) |
| 135 | + lastIndex := 0 |
| 136 | + |
| 137 | + for _, match := range hexEntityPat.FindAllSubmatchIndex(input, -1) { |
| 138 | + startIndex := match[0] |
| 139 | + endIndex := match[1] |
| 140 | + hexStartIndex := match[2] |
| 141 | + hexEndIndex := match[3] |
| 142 | + |
| 143 | + // Copy the part of the input until the start of the entity |
| 144 | + decoded = append(decoded, input[lastIndex:startIndex]...) |
| 145 | + |
| 146 | + // Parse the hexadecimal value to an integer |
| 147 | + num, err := strconv.ParseInt(string(input[hexStartIndex:hexEndIndex]), 16, 32) |
| 148 | + if err != nil { |
| 149 | + continue |
| 150 | + } |
| 151 | + |
| 152 | + // Append the decoded byte |
| 153 | + if num < 0 || num > 255 { |
| 154 | + logger.Error(errors.New("invalid hex byte"), "Unable to decode HTML entity", "match", input[hexStartIndex:hexEndIndex], "byte", num) |
| 155 | + continue |
| 156 | + } |
| 157 | + decoded = append(decoded, byte(num)) |
| 158 | + |
| 159 | + lastIndex = endIndex |
| 160 | + } |
| 161 | + |
| 162 | + // Append the remaining part of the input |
| 163 | + decoded = append(decoded, input[lastIndex:]...) |
| 164 | + |
| 165 | + return decoded |
| 166 | +} |
| 167 | + |
| 168 | +var ( |
| 169 | + // https://www.compart.com/en/unicode/html |
| 170 | + namedEntityMap = map[string][]byte{ |
| 171 | + "&tab;": []byte(" "), |
| 172 | + "&newline;": []byte("\n"), |
| 173 | + "!": []byte("!"), |
| 174 | + """: []byte(`"`), |
| 175 | + "#": []byte("#"), |
| 176 | + "$": []byte("$"), |
| 177 | + "%": []byte("%"), |
| 178 | + "&": []byte("&"), |
| 179 | + "'": []byte("'"), |
| 180 | + "(": []byte("("), |
| 181 | + ")": []byte(")"), |
| 182 | + "*": []byte("*"), |
| 183 | + "+": []byte("+"), |
| 184 | + ",": []byte(","), |
| 185 | + ".": []byte("."), |
| 186 | + "/": []byte("/"), |
| 187 | + ":": []byte(":"), |
| 188 | + ";": []byte(";"), |
| 189 | + "<": []byte("<"), |
| 190 | + "=": []byte("="), |
| 191 | + ">": []byte(">"), |
| 192 | + "?": []byte("?"), |
| 193 | + "@": []byte("@"), |
| 194 | + "[": []byte("["), |
| 195 | + "\": []byte("\\"), |
| 196 | + "]": []byte("]"), |
| 197 | + "&hat;": []byte("^"), |
| 198 | + "&underbar;": []byte("_"), |
| 199 | + "&diacriticalgrave;": []byte("`"), |
| 200 | + "{": []byte("{"), |
| 201 | + "&verticalline;": []byte("|"), |
| 202 | + "}": []byte("}"), |
| 203 | + "&nonbreakingspace;": []byte(" "), |
| 204 | + } |
| 205 | + namedEntityPat = func() *regexp.Regexp { |
| 206 | + return regexp.MustCompile( |
| 207 | + "(?i)(" + strings.Join(maps.Keys(namedEntityMap), "|") + ")") |
| 208 | + }() |
| 209 | +) |
| 210 | + |
| 211 | +func decodeNamedEntities(_ logr.Logger, input []byte) []byte { |
| 212 | + return namedEntityPat.ReplaceAllFunc(input, func(match []byte) []byte { |
| 213 | + m := strings.ToLower(string(match)) |
| 214 | + if replacement, ok := namedEntityMap[m]; ok { |
| 215 | + return replacement |
| 216 | + } |
| 217 | + return match |
| 218 | + }) |
| 219 | +} |
0 commit comments