pcapDecoder allows .hex files as input. Make public some Avp methods for serializatio...
[anna.git] / example / diameter / pcapDecoder / main.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // http://redmine.teslayout.com/projects/anna-suite
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
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
16 // distribution.
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.
20 //
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.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36 // Standard
37 #include <pcap.h>
38 #include <stdlib.h>
39 #include <netinet/ip.h>
40 #include <arpa/inet.h>
41 #include <iostream>
42 #include <fstream>
43
44 // STL
45 #include <string>
46 #include <map>
47
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>
58
59 using namespace anna;
60 using namespace anna::diameter;
61
62 // Payload and frame metadata /////////////////////////////////////////////////////////////////////////////
63 class Payload {
64
65   std::string _sourceIP;
66   std::string _destinationIP;
67   time_t _timestamp;
68   int _timestampU; // usecs
69   std::string _data;
70   size_t _diameterLength;
71
72 public:
73   Payload() {
74     reset();
75   }
76
77   void setDiameterLength(size_t dl) {
78     if(_diameterLength == -1) {
79       _diameterLength = dl;
80       LOGDEBUG(
81         Logger::debug(anna::functions::asString("Diameter message length: %d bytes", dl), ANNA_FILE_LOCATION));
82     }
83   }
84
85   void setSourceIP(const std::string &srcIP) throw() {
86     _sourceIP = srcIP;
87   }
88   void setDestinationIP(const std::string &dstIP) throw() {
89     _destinationIP = dstIP;
90   }
91   void setTimestamp(time_t ts) throw() {
92     _timestamp = ts;
93   }
94   void setTimestampU(int tsu) throw() {
95     _timestampU = tsu;
96   }
97   // Returns true if completed:
98   bool appendData(const char *data, size_t size) throw(RuntimeException) {
99     LOGDEBUG(
100       Logger::debug(anna::functions::asString("Appending %d bytes", size), ANNA_FILE_LOCATION));
101     _data.append(data, size);
102
103     if(_data.size() > _diameterLength)
104       throw RuntimeException(
105         "Data overflow (unexpected offset exceed diameter message length)",
106         ANNA_FILE_LOCATION);
107
108     if(_data.size() < _diameterLength)
109       return false;
110
111     LOGDEBUG(anna::Logger::debug("Completed!", ANNA_FILE_LOCATION));
112     return true;
113   }
114
115   void reset() throw() {
116     _sourceIP = "";
117     _destinationIP = "";
118     _timestamp = 0;
119     _timestampU = 0;
120     _data = "";
121     _diameterLength = -1; // not calculated yet
122   }
123
124   const std::string &getSourceIP() const throw() {
125     return _sourceIP;
126   }
127   const std::string &getDestinationIP() const throw() {
128     return _destinationIP;
129   }
130   time_t getTimestamp() const throw() {
131     return _timestamp;
132   }
133   int getTimestampU() const throw() {
134     return _timestampU;
135   }
136   const std::string &getData() const throw() {
137     return _data;
138   }
139   std::string getDataAsHex() const throw() {
140     return anna::functions::asHexString(
141              anna::DataBlock(_data.c_str(), _data.size()));
142   }
143 };
144
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;
150
151 // Sniffing structures ////////////////////////////////////////////////////////////////////////////////////
152
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
157
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 */
163 };
164
165 /* IP header */
166 struct sniff_ip {
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 */
180 };
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)
186
187 /* TCP header */
188 typedef u_int tcp_seq;
189
190 struct sniff_tcp {
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)
197   u_char th_flags;
198 #define TH_FIN 0x01
199 #define TH_SYN 0x02
200 #define TH_RST 0x04
201 #define TH_PUSH 0x08
202 #define TH_ACK 0x10
203 #define TH_URG 0x20
204 #define TH_ECE 0x40
205 #define TH_CWR 0x80
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 */
210 };
211
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 */
219   u_int size_ip;
220   u_int size_tcp;
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
224
225   if(size_ip < 20) {
226     LOGDEBUG(
227       Logger::debug(anna::functions::asString("Invalid IP header length: %d bytes", size_ip), ANNA_FILE_LOCATION));
228     return NULL;
229   }
230
231   static char str[INET_ADDRSTRLEN];
232   inet_ntop(AF_INET, &(ip->ip_src), str, INET_ADDRSTRLEN);
233   srcIp = str;
234   inet_ntop(AF_INET, &(ip->ip_dst), str, INET_ADDRSTRLEN);
235   dstIp = str;
236   LOGDEBUG(
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;
244
245   if(size_tcp < 20) {
246     LOGDEBUG(
247       Logger::debug(anna::functions::asString("Invalid TCP header length: %d bytes", size_tcp), ANNA_FILE_LOCATION));
248     return NULL;
249   }
250
251   int payloadOffset = SIZE_ETHERNET + size_ip + size_tcp;
252   LOGDEBUG(
253     Logger::debug(anna::functions::asString("PayloadOffset=%d", payloadOffset), ANNA_FILE_LOCATION));
254   payloadSize = packetSize - payloadOffset;
255   return ((u_char *)(packet + payloadOffset));
256 }
257
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;
264   int payloadSize;
265   std::string srcIp, dstIp;
266   int fragmentId, fragmentOffset;
267   bool dfFlag, mfFlag;
268   const u_char* payload = getPayload(packet, packetSize, payloadSize, srcIp,
269                                      dstIp, fragmentId, dfFlag, mfFlag, fragmentOffset);
270
271   if(payload && (payloadSize > 0)) {
272     LOGDEBUG(
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);
282
283     if(completed) {
284       G_payloads[count] = auxPayload;
285       auxPayload.reset();
286     }
287   }
288
289   count++;
290 }
291
292 bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) throw() {
293
294   // Get hex string
295   static char buffer[8192];
296   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
297   if(infile.is_open()) {
298     infile >> buffer;
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());
302     LOGDEBUG(
303       std::string msg = "Hex string (remove colons if exists): ";
304       msg += hexString;
305       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
306     );
307
308     anna::functions::fromHexString(hexString, db);
309     // Close file
310     infile.close();
311     return true;
312   }
313
314   return false;
315 }
316
317
318 void _exit(const std::string &message, int resultCode = 1) {
319   if (resultCode)
320     std::cerr << message << std::endl << std::endl;
321   else
322     std::cout << message << std::endl << std::endl;
323   exit(resultCode);
324 }
325
326
327 //-------------------------------------------------------------------
328 int main(int argc, char **argv) {
329   std::string exec = argv[0];
330   std::cout << std::endl;
331
332   //check command line arguments
333   if(argc < 3) {
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).";
338     _exit(msg);
339   }
340
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();
359
360   try {
361     anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(
362         0 /* stack id */);
363     // Analyze comma-separated list:
364     anna::Tokenizer lst;
365     lst.apply(dictionaries, ",");
366
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;
372       d->allowUpdates();
373
374       for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
375         pathFile = anna::Tokenizer::data(tok_iter);
376         d->load(pathFile);
377       }
378     }
379
380     codecEngine->setDictionary(d);
381     //LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
382
383     if(lst.size() > 1) {
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());
388       out.close();
389       std::cout << "Written accumulated '" << all_in_one
390                 << "' (provide it next time to be more comfortable)." << std::endl;
391     }
392   } catch(anna::RuntimeException &ex) {
393     _exit(ex.asString());
394   }
395
396   codecEngine->ignoreFlagsOnValidation(ignoreFlags);
397   // Tracing:
398   //if (cl.exists("trace"))
399   //   anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
400
401   // Check hex content input file (look extension):
402   anna::DataBlock db_aux(true);
403   if(isHex) {
404     if (!getDataBlockFromHexFile(inputFile, db_aux))
405       _exit("Error reading hex file provided");
406
407     try {
408       G_codecMsg.decode(db_aux);
409     } catch(RuntimeException &ex) {
410       _exit(ex.asString());
411     }
412
413     // Open output file:
414     outputFile += ".as.xml";
415     std::ofstream out(outputFile, std::ifstream::out);
416     out << G_codecMsg.asXMLString();
417
418     // Close output file:
419     out.close();
420
421     std::string msg = "Open 'file.trace' in order to see process traces.\n";
422     msg += "Open '"; msg += outputFile; msg += "' to see decoding results.";
423     _exit(msg, 0);
424   }
425
426   // Normal input: pcap file:
427
428   // SNIFFING //////////////////////////////////////////////////////////////////////////////////////////////7
429   //temporary packet buffers
430   struct pcap_pkthdr header; // The header that pcap gives us
431   const u_char *packet;      // The actual packet
432   //------------------
433   //open the pcap file
434   pcap_t *handle;
435   char errbuf[PCAP_ERRBUF_SIZE];        //not sure what to do with this, oh well
436   handle = pcap_open_offline(inputFile.c_str(), errbuf); //call pcap library function
437
438   if(handle == NULL) _exit(errbuf, 2);
439
440   //begin processing the packets in this particular file
441   int packets = -1;
442
443   try {
444     while(packets != 0)
445       packets = pcap_dispatch(handle, -1, (pcap_handler) my_callback, NULL);
446   } catch(RuntimeException &ex) {
447     _exit(ex.asString());
448   }
449
450   pcap_close(handle);  //close the pcap file
451   // Print payloads //////////////////////////////////////////////////////////////////////////////////////////////
452   // Open output file:
453   outputFile += ".report";
454   std::ofstream out(outputFile, std::ifstream::out);
455
456   for(payloads_it it = G_payloads.begin(); it != G_payloads.end(); it++) {
457     LOGDEBUG(
458       Logger::debug(anna::functions::asString("Dumping frame %d", it->first), ANNA_FILE_LOCATION));
459     time_t ts = (it->second).getTimestamp();
460     int tsu = (it->second).getTimestampU();
461     std::string ts_str = ctime(&ts);
462     ts_str.erase(ts_str.find("\n"));
463     out << std::endl;
464     out
465         << "==================================================================================================="
466         << std::endl;
467     out << "Date:           " << ts_str << std::endl;
468     out << "Timestamp:      " << std::to_string(ts) << "."
469         << std::to_string(tsu) << std::endl;
470     out << "Origin IP:      " << (it->second).getSourceIP() << std::endl;
471     out << "Destination IP: " << (it->second).getDestinationIP() << std::endl;
472     out << std::endl;
473     // decode hex string:
474     anna::functions::fromHexString((it->second).getDataAsHex(), db_aux);
475
476     try {
477       G_codecMsg.decode(db_aux);
478     } catch(RuntimeException &ex) {
479       _exit(ex.asString());
480     }
481
482     out << G_codecMsg.asXMLString();
483   }
484
485   // Close output file:
486   out.close();
487
488   std::string msg = "Open 'file.trace' in order to see process traces.\n";
489   msg += "Open '"; msg += outputFile; msg += "' to see decoding results.";
490   _exit(msg, 0);
491 }
492