Hi there,
I'm trying to match a portion of a network packet (captured with libpcap) using RegEx. In this case, I want to identify if the packet is a DNS packet. Here is an example trace that I would like to match:
Code:
15:29:26.792551 IP 70.85.31.142.32868 > 67.18.92.7.53: 11852+ A? www.cnn.com. (29)
0x0000: 4500 0039 0000 4000 4011 35b8 4655 1f8e
0x0010: 4312 5c07 8064 0035 0025 e930 2e4c 0100
0x0020: 0001 0000 0000 0000 0377 7777 0363 6e6e
0x0030: 0363 6f6d 0000 0100 01
The www.cnn.com is pretty clear (77 7777 0363 6e6e 0363 6fdf). And I believe the third character from the end (0x01 - two bytes after the end of the domain name) indicates this is an A record request.
A regex of:
Code:
\\x63\\x6f\\x6d\\x00\\x00\\x01
should match this packet, but I can't seem to get it to work. Any ideas? Here is the code (note that the other matches work fine, but they are just matching ASCII characters):
Code:
#include <sys/types.h>
#include <regex.h>
#include "../common/common.h"
_Bool is_http(const u_char * payload);
_Bool is_ldap(const u_char * payload);
_Bool is_syslog(const u_char * payload);
_Bool is_dns(const u_char * payload);
_Bool evaluate(const u_char * payload, regex_t * pattern);
regex_t http_compiled, ldap_compiled, syslog_compiled, dns_compiled;
_Bool compiled = 0;
void compile() {
regcomp (&http_compiled, "(GET / HTTP)|(HTTP/1\\.1)", REG_EXTENDED);
regcomp (&ldap_compiled, "(cn=\\w*,?)|(dc=\\w*,?)|(ou=\\w*,?)", REG_EXTENDED);
regcomp (&syslog_compiled, "<[0-9][0-9]?>\\w|/", REG_EXTENDED);
regcomp (&dns_compiled, "\\x63\\x6f\\x6d\\x00\\x00\\x01", REG_EXTENDED); //matches 'A' record for .com
compiled = 1;
}
_Bool is_http(const u_char * payload) {
if(!compiled) compile();
return(evaluate(payload, &http_compiled));
}
_Bool is_ldap(const u_char * payload) {
if(!compiled) compile();
return(evaluate(payload, &ldap_compiled));
}
_Bool is_syslog(const u_char * payload) {
if(!compiled) compile();
return(evaluate(payload, &syslog_compiled));
}
_Bool is_dns(const u_char * payload) {
if(!compiled) compile();
return(evaluate(payload, &dns_compiled));
}
_Bool evaluate(const u_char * payload, regex_t * pattern) {
if((regexec (pattern, payload, 0, NULL, 0)) == 0) {
return 1;
} else return 0;
}
Thanks in advance for your help!