I've seen many similar questions but no answer.
Basically I'm trying to grep hardcoded private key in 1000s of files to find malicious ones and skip legitimate, that define this string as variable.
So I want to match all files that have "BEGIN PRIVATE KEY-----" and 1x or 0x CR and end of line. so I've tried all sorts of greps, but nothing really works I expected that this would work
# grep -iIREn "BEGIN PRIVATE KEY-----\r" /tmp/hck-bck/
grep: warning: stray \ before r
# grep -iIREn "BEGIN PRIVATE KEY-----" /tmp/hck-bck/
/tmp/hck-bck/style.php:123:$privateKey = '-----BEGIN PRIVATE KEY-----
# grep -iIREn "BEGIN PRIVATE KEY-----(\r)" /tmp/hck-bck/
grep: warning: stray \ before r
# grep -iIREn "BEGIN PRIVATE KEY-----[[:cntrl:]]" /tmp/hck-bck/
# grep -iIREn "BEGIN PRIVATE KEY-----[[:cntrl:]]?$" /tmp/hck-bck/
# grep -iIREn "BEGIN PRIVATE KEY-----.$" /tmp/hck-bck/
# grep -iIREn "BEGIN PRIVATE KEY-----$" /tmp/hck-bck/
# grep -iIREn 'BEGIN PRIVATE KEY-----[\r]' /tmp/hck-bck/
# grep -iIREn 'BEGIN PRIVATE KEY-----[[:cntrl:]]?$' /tmp/hck-bck/
# grep -iIREn "BEGIN PRIVATE KEY-----\\r" /tmp/hck-bck/
grep: warning: stray \ before r
#
So if I put nothing after last dash (-), then I'll have many false positives.
Using[:
cntrl:] actually matches, but it doesn't output anything so, I can't tell in log which file was it. Using '\r' which is suppose to work for CR outputs warning and no match. I've tried single and double quotes.If I use -P instead of -E also no difference. Using '\r' would actually match literal \r as part of string defined in some php files.
#cat -A style.php
....
}^M$
$privateKey = '-----BEGIN PRIVATE KEY-----^M$
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC30w49ItOfldQ6^M$
dB+0gEbeeW6BEClcx+NZzmpX2YcRHFV80BurCWBavPFehV8Sy9yL2u/y3mv3QJJ+^M$
x2kKvly8zKx4GbXPbsWJk6Ho0Rxq49oXkBarQBOqROZeaFF3Mzpd/PdLSsxEvG1M^M$
tQd2wOx5r6XD86jyfN7LAJUUVvbJvn1CHo03nFH12k1KYwLnQfzQI5nX7yQLa0jt^M$
fG5TA34Fm0EMbFdHWjAN/VdEjoJI6it4PCQP5wk4ga2BvVquQkuPbsbr8364d3I6^M$
GuGAKDR0wfkT20n0E6kAmDI3ol2bfa0rQncqUS3OU3INpxOZS8eKCIgC3bM81mdi^M$
MQ6TsAQ9AgMBAAECggEAJLGSlA2RpLdpx8lKUuOQQfSHZGfveb/E2DZl7+dSGM5J^M$
.............
So file has a CR and end of line. Why does using [:cntrl:] show no matched output? And how to properly specify CR after last dash to get match?
adding output to some suggestions
# grep -ERn $'BEGIN PRIVATE KEY-----\r?$' /tmp/hck-bck/
# grep -ERn $'BEGIN PRIVATE KEY-----.$' /tmp/hck-bck/
# grep -ERn $'BEGIN PRIVATE KEY-----' /tmp/hck-bck/
/tmp/hck-bck/style.php:123:$privateKey = '-----BEGIN PRIVATE KEY-----
#
grep -R --color=never -l -E $'BEGIN PRIVATE KEY-----\r?$' /tmp/hck-bck/
Use $'...'
so that C-style escape sequences will be processed in the string; this is needed to convert \r
to a CR character.
$
matches the end of the line, and \r?
matches an optional CR characters before it.
--color=never
is needed to avoid problems with interaction between coloring the output and printing the CR characters.