1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
39 #include <netinet/ip.h>
40 #include <arpa/inet.h>
48 #include <anna/core/DataBlock.hpp>
49 #include <anna/core/util/Tokenizer.hpp>
50 #include <anna/core/functions.hpp>
51 #include <anna/core/tracing/Logger.hpp>
52 #include <anna/core/tracing/TraceWriter.hpp>
53 #include <anna/core/RuntimeException.hpp>
54 #include <anna/xml/xml.hpp>
55 #include <anna/diameter/stack/Engine.hpp>
56 #include <anna/diameter/codec/Engine.hpp>
57 #include <anna/diameter/codec/Message.hpp>
60 using namespace anna::diameter;
62 // Payload and frame metadata /////////////////////////////////////////////////////////////////////////////
65 std::string _sourceIP;
66 std::string _destinationIP;
68 int _timestampU; // usecs
70 size_t _diameterLength;
77 void setDiameterLength(size_t dl) {
78 if(_diameterLength == -1) {
81 Logger::debug(anna::functions::asString("Diameter message length: %d bytes", dl), ANNA_FILE_LOCATION));
85 void setSourceIP(const std::string &srcIP) throw() {
88 void setDestinationIP(const std::string &dstIP) throw() {
89 _destinationIP = dstIP;
91 void setTimestamp(time_t ts) throw() {
94 void setTimestampU(int tsu) throw() {
97 // Returns true if completed:
98 bool appendData(const char *data, size_t size) throw(RuntimeException) {
100 Logger::debug(anna::functions::asString("Appending %d bytes", size), ANNA_FILE_LOCATION));
101 _data.append(data, size);
103 if(_data.size() > _diameterLength)
104 throw RuntimeException(
105 "Data overflow (unexpected offset exceed diameter message length)",
108 if(_data.size() < _diameterLength)
111 LOGDEBUG(anna::Logger::debug("Completed!", ANNA_FILE_LOCATION));
115 void reset() throw() {
121 _diameterLength = -1; // not calculated yet
124 const std::string &getSourceIP() const throw() {
127 const std::string &getDestinationIP() const throw() {
128 return _destinationIP;
130 time_t getTimestamp() const throw() {
133 int getTimestampU() const throw() {
136 const std::string &getData() const throw() {
139 std::string getDataAsHex() const throw() {
140 return anna::functions::asHexString(
141 anna::DataBlock(_data.c_str(), _data.size()));
145 // Data maps //////////////////////////////////////////////////////////////////////////////////////////////
146 typedef std::map < int /* frame */, Payload > payloads_t;
147 typedef std::map < int /* frame */, Payload >::const_iterator payloads_it;
148 payloads_t G_payloads;
149 anna::diameter::codec::Message G_codecMsg;
151 // Sniffing structures ////////////////////////////////////////////////////////////////////////////////////
153 /* ethernet headers are always exactly 14 bytes */
154 #define SIZE_ETHERNET 14
155 /* Ethernet addresses are 6 bytes */
156 #define ETHER_ADDR_LEN 6
158 /* Ethernet header */
159 struct sniff_ethernet {
160 u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
161 u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
162 u_short ether_type; /* IP? ARP? RARP? etc */
167 u_char ip_vhl; /* version << 4 | header length >> 2 */
168 u_char ip_tos; /* type of service */
169 u_short ip_len; /* total length */
170 u_short ip_id; /* identification */
171 u_short ip_off; /* fragment offset field */
172 #define IP_RF 0x8000 /* reserved fragment flag */
173 #define IP_DF 0x4000 /* dont fragment flag */
174 #define IP_MF 0x2000 /* more fragments flag */
175 #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
176 u_char ip_ttl; /* time to live */
177 u_char ip_p; /* protocol */
178 u_short ip_sum; /* checksum */
179 struct in_addr ip_src, ip_dst; /* source and dest address */
181 #define IP_OFF(ip) (((ip)->ip_off) & IP_OFFMASK)
182 #define IP_DF_VAL(ip) ((((ip)->ip_off) & IP_DF) >> 14)
183 #define IP_MF_VAL(ip) ((((ip)->ip_off) & IP_MF) >> 13)
184 #define IP_HL(ip) (((ip)->ip_vhl) & 0x0f)
185 #define IP_V(ip) (((ip)->ip_vhl) >> 4)
188 typedef u_int tcp_seq;
191 u_short th_sport; /* source port */
192 u_short th_dport; /* destination port */
193 tcp_seq th_seq; /* sequence number */
194 tcp_seq th_ack; /* acknowledgement number */
195 u_char th_offx2; /* data offset, rsvd */
196 #define TH_OFF(th) (((th)->th_offx2 & 0xf0) >> 4)
206 #define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
207 u_short th_win; /* window */
208 u_short th_sum; /* checksum */
209 u_short th_urp; /* urgent pointer */
212 // Payload extraction /////////////////////////////////////////////////////////////////////////////////////
213 u_char *getPayload(const u_char* packet, int packetSize, int &payloadSize,
214 std::string &srcIp, std::string &dstIp, int &fragmentId, bool &dfFlag,
215 bool &mfFlag, int &fragmentOffset) {
216 const struct sniff_ethernet *ethernet; /* The ethernet header */
217 const struct sniff_ip *ip; /* The IP header */
218 const struct sniff_tcp *tcp; /* The TCP header */
221 ethernet = (struct sniff_ethernet*)(packet);
222 ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
223 size_ip = IP_HL(ip) * 4; // 4 bytes per 32 bits word
227 Logger::debug(anna::functions::asString("Invalid IP header length: %d bytes", size_ip), ANNA_FILE_LOCATION));
231 static char str[INET_ADDRSTRLEN];
232 inet_ntop(AF_INET, &(ip->ip_src), str, INET_ADDRSTRLEN);
234 inet_ntop(AF_INET, &(ip->ip_dst), str, INET_ADDRSTRLEN);
237 Logger::debug(anna::functions::asString("ip_id: %d | ip_off: %d", ip->ip_id, ip->ip_off), ANNA_FILE_LOCATION));
238 fragmentId = ip->ip_id;
239 dfFlag = IP_DF_VAL(ip);
240 mfFlag = IP_MF_VAL(ip);
241 fragmentOffset = IP_OFF(ip);
242 tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
243 size_tcp = TH_OFF(tcp) * 4;
247 Logger::debug(anna::functions::asString("Invalid TCP header length: %d bytes", size_tcp), ANNA_FILE_LOCATION));
251 int payloadOffset = SIZE_ETHERNET + size_ip + size_tcp;
253 Logger::debug(anna::functions::asString("PayloadOffset=%d", payloadOffset), ANNA_FILE_LOCATION));
254 payloadSize = packetSize - payloadOffset;
255 return ((u_char *)(packet + payloadOffset));
258 // Sniffing callback //////////////////////////////////////////////////////////////////////////////////////
259 void my_callback(u_char *useless, const struct pcap_pkthdr* pkthdr,
260 const u_char* packet) {
261 static int count = 1;
262 static Payload auxPayload;
263 int packetSize = pkthdr->len;
265 std::string srcIp, dstIp;
266 int fragmentId, fragmentOffset;
268 const u_char* payload = getPayload(packet, packetSize, payloadSize, srcIp,
269 dstIp, fragmentId, dfFlag, mfFlag, fragmentOffset);
271 if(payload && (payloadSize > 0)) {
273 std::string msg; msg += anna::functions::asString("\nFrame %d:", count); msg += anna::functions::asHexString(anna::DataBlock((const char *)packet, pkthdr->len)); time_t time = pkthdr->ts.tv_sec; msg += "\n"; msg += anna::functions::asString("\ntimestamp %d.%d", pkthdr->ts.tv_sec, pkthdr->ts.tv_usec); msg += anna::functions::asString("\ndate %s", ctime(&time)); msg += anna::functions::asString("\ncaplen %d", pkthdr->caplen); msg += anna::functions::asString("\npacketSize %d", packetSize); msg += anna::functions::asString("\npayloadSize %d", payloadSize); msg += "\nPayload:"; msg += anna::functions::asHexString(anna::DataBlock((const char *)payload, payloadSize)); msg += "\n"; msg += anna::functions::asString("\nsourceIP %s", srcIp.c_str()); msg += anna::functions::asString("\ndestinationIP %s", dstIp.c_str()); msg += "\n"; msg += anna::functions::asString("\nfragmentId %d:", fragmentId); msg += anna::functions::asString("\nDF %s:", (dfFlag ? "1" : "0")); msg += anna::functions::asString("\nMF %s:", (mfFlag ? "1" : "0")); msg += anna::functions::asString("\nfragmentOffset %d:", fragmentOffset);
274 Logger::debug(msg, ANNA_FILE_LOCATION););
275 auxPayload.setDiameterLength(
276 (payload[1] << 16) + (payload[2] << 8) + payload[3]);
277 auxPayload.setSourceIP(srcIp);
278 auxPayload.setDestinationIP(dstIp);
279 auxPayload.setTimestamp(pkthdr->ts.tv_sec);
280 auxPayload.setTimestampU(pkthdr->ts.tv_usec);
281 bool completed = auxPayload.appendData((const char *) payload, payloadSize);
284 G_payloads[count] = auxPayload;
292 bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) throw() {
294 static char buffer[8192];
295 std::ifstream infile(pathfile.c_str(), std::ifstream::in);
297 if(infile.is_open()) {
299 std::string hexString(buffer, strlen(buffer));
300 // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
301 hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
303 std::string msg = "Hex string (remove colons if exists): ";
305 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
307 anna::functions::fromHexString(hexString, db);
317 void _exit(const std::string &message, int resultCode = 1) {
319 std::cerr << message << std::endl << std::endl;
321 std::cout << message << std::endl << std::endl;
327 //-------------------------------------------------------------------
328 int main(int argc, char **argv) {
329 std::string exec = argv[0];
330 std::cout << std::endl;
332 //check command line arguments
334 std::string msg = "Usage: "; msg += exec;
335 msg += " <dictionaries> <input file> [--ignore-flags: non-strict validation]\n\n";
336 msg += " dictionaries: list of comma-separated xml dictionaries (one or more can be provided).\n";
337 msg += " Input file: normally a pcap file, but hexadecimal content (colons allowed) can also be decoded (use '.hex' extension).";
341 // Command-line parameters:
342 std::string dictionaries = argv[1];
343 std::string inputFile = argv[2];
344 bool isHex = (inputFile.substr(inputFile.find_last_of(".") + 1) == "hex");
345 std::string outputFile = inputFile; // extension will be added later
346 std::string optional = argv[3] ? argv[3] : "";
347 bool ignoreFlags = ((argc == 4) && (optional == "--ignore-flags"));
348 std::cout << "Dictionary(ies) provided: " << dictionaries << std::endl;
349 std::cout << "Input file provided: " << inputFile << std::endl;
350 std::cout << "Validation kindness: "
351 << (ignoreFlags ? "non strict" : "strict") << std::endl;
352 // Logger and engines:
353 Logger::setLevel(Logger::Debug);
354 Logger::initialize("pcapDecoder", new TraceWriter("file.trace", 2048000));
355 anna::diameter::codec::Engine *codecEngine =
356 new anna::diameter::codec::Engine();
357 anna::diameter::stack::Engine &stackEngine =
358 anna::diameter::stack::Engine::instantiate();
361 anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(
363 // Analyze comma-separated list:
365 lst.apply(dictionaries, ",");
367 if(lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
368 anna::Tokenizer::const_iterator tok_min(lst.begin());
369 anna::Tokenizer::const_iterator tok_max(lst.end());
370 anna::Tokenizer::const_iterator tok_iter;
371 std::string pathFile;
374 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
375 pathFile = anna::Tokenizer::data(tok_iter);
380 codecEngine->setDictionary(d);
381 //LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
384 std::string all_in_one = "./dictionary-all-in-one.xml";
385 std::ofstream out(all_in_one, std::ifstream::out);
386 std::string buffer = d->asXMLString();
387 out.write(buffer.c_str(), buffer.size());
389 std::cout << "Written accumulated '" << all_in_one
390 << "' (provide it next time to be more comfortable)." << std::endl;
392 } catch(anna::RuntimeException &ex) {
393 _exit(ex.asString());
396 codecEngine->ignoreFlagsOnValidation(ignoreFlags);
398 //if (cl.exists("trace"))
399 // anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
400 // Check hex content input file (look extension):
401 anna::DataBlock db_aux(true);
404 if(!getDataBlockFromHexFile(inputFile, db_aux))
405 _exit("Error reading hex file provided");
408 G_codecMsg.decode(db_aux);
409 } catch(RuntimeException &ex) {
410 _exit(ex.asString());
414 outputFile += ".as.xml";
415 std::ofstream out(outputFile, std::ifstream::out);
416 out << G_codecMsg.asXMLString();
417 // Close output file:
419 std::string msg = "Open 'file.trace' in order to see process traces.\n";
420 msg += "Open '"; msg += outputFile; msg += "' to see decoding results.";
424 // Normal input: pcap file:
425 // SNIFFING //////////////////////////////////////////////////////////////////////////////////////////////7
426 //temporary packet buffers
427 struct pcap_pkthdr header; // The header that pcap gives us
428 const u_char *packet; // The actual packet
432 char errbuf[PCAP_ERRBUF_SIZE]; //not sure what to do with this, oh well
433 handle = pcap_open_offline(inputFile.c_str(), errbuf); //call pcap library function
435 if(handle == NULL) _exit(errbuf, 2);
437 //begin processing the packets in this particular file
442 packets = pcap_dispatch(handle, -1, (pcap_handler) my_callback, NULL);
443 } catch(RuntimeException &ex) {
444 _exit(ex.asString());
447 pcap_close(handle); //close the pcap file
448 // Print payloads //////////////////////////////////////////////////////////////////////////////////////////////
450 outputFile += ".report";
451 std::ofstream out(outputFile, std::ifstream::out);
453 for(payloads_it it = G_payloads.begin(); it != G_payloads.end(); it++) {
455 Logger::debug(anna::functions::asString("Dumping frame %d", it->first), ANNA_FILE_LOCATION));
456 time_t ts = (it->second).getTimestamp();
457 int tsu = (it->second).getTimestampU();
458 std::string ts_str = ctime(&ts);
459 ts_str.erase(ts_str.find("\n"));
462 << "==================================================================================================="
464 out << "Date: " << ts_str << std::endl;
465 out << "Timestamp: " << std::to_string(ts) << "."
466 << std::to_string(tsu) << std::endl;
467 out << "Origin IP: " << (it->second).getSourceIP() << std::endl;
468 out << "Destination IP: " << (it->second).getDestinationIP() << std::endl;
470 // decode hex string:
471 anna::functions::fromHexString((it->second).getDataAsHex(), db_aux);
474 G_codecMsg.decode(db_aux);
475 } catch(RuntimeException &ex) {
476 _exit(ex.asString());
479 out << G_codecMsg.asXMLString();
482 // Close output file:
484 std::string msg = "Open 'file.trace' in order to see process traces.\n";
485 msg += "Open '"; msg += outputFile; msg += "' to see decoding results.";