Remove warnings
[anna.git] / example / diameter / pcapDecoder / main.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 #include <pcap.h>
10 #include <stdlib.h>
11 #include <netinet/ip.h>
12 #include <arpa/inet.h>
13 #include <iostream>
14 #include <fstream>
15
16 // STL
17 #include <string>
18 #include <map>
19
20 #include <anna/core/DataBlock.hpp>
21 #include <anna/core/functions.hpp>
22 #include <anna/core/tracing/Logger.hpp>
23 #include <anna/core/tracing/TraceWriter.hpp>
24 #include <anna/core/RuntimeException.hpp>
25
26
27 using namespace anna;
28
29 // Payload and frame metadata /////////////////////////////////////////////////////////////////////////////
30 class Payload {
31
32   std::string _sourceIP;
33   std::string _destinationIP;
34   time_t _timestamp;
35   int _timestampU; // usecs
36   std::string _data;
37   size_t _diameterLength;
38
39 public:
40   Payload() {
41     reset();
42   }
43
44   void setDiameterLength(size_t dl) {
45     if(_diameterLength == -1) {
46       _diameterLength = dl;
47       LOGDEBUG(
48         Logger::debug(anna::functions::asString("Diameter message length: %d bytes", dl), ANNA_FILE_LOCATION));
49     }
50   }
51
52   void setSourceIP(const std::string &srcIP) throw() {
53     _sourceIP = srcIP;
54   }
55   void setDestinationIP(const std::string &dstIP) throw() {
56     _destinationIP = dstIP;
57   }
58   void setTimestamp(time_t ts) throw() {
59     _timestamp = ts;
60   }
61   void setTimestampU(int tsu) throw() {
62     _timestampU = tsu;
63   }
64   // Returns true if completed:
65   bool appendData(const char *data, size_t size) throw(RuntimeException) {
66     LOGDEBUG(
67       Logger::debug(anna::functions::asString("Appending %d bytes", size), ANNA_FILE_LOCATION));
68     _data.append(data, size);
69
70     if(_data.size() > _diameterLength)
71       throw RuntimeException(
72         "Data overflow (unexpected offset exceed diameter message length)",
73         ANNA_FILE_LOCATION);
74
75     if(_data.size() < _diameterLength)
76       return false;
77
78     LOGDEBUG(anna::Logger::debug("Completed!", ANNA_FILE_LOCATION));
79     return true;
80   }
81
82   void reset() throw() {
83     _sourceIP = "";
84     _destinationIP = "";
85     _timestamp = 0;
86     _timestampU = 0;
87     _data = "";
88     _diameterLength = -1; // not calculated yet
89   }
90
91   const std::string &getSourceIP() const throw() {
92     return _sourceIP;
93   }
94   const std::string &getDestinationIP() const throw() {
95     return _destinationIP;
96   }
97   time_t getTimestamp() const throw() {
98     return _timestamp;
99   }
100   int getTimestampU() const throw() {
101     return _timestampU;
102   }
103   const std::string &getData() const throw() {
104     return _data;
105   }
106   std::string getDataAsHex() const throw() {
107     return anna::functions::asHexString(
108              anna::DataBlock(_data.c_str(), _data.size()));
109   }
110 };
111
112 // Data maps //////////////////////////////////////////////////////////////////////////////////////////////
113 typedef std::map < int /* frame */, Payload > payloads_t;
114 typedef std::map < int /* frame */, Payload >::const_iterator payloads_it;
115 payloads_t G_payloads;
116
117 // Sniffing structures ////////////////////////////////////////////////////////////////////////////////////
118
119 /* ethernet headers are always exactly 14 bytes */
120 #define SIZE_ETHERNET 14
121 /* Ethernet addresses are 6 bytes */
122 #define ETHER_ADDR_LEN  6
123
124 /* Ethernet header */
125 struct sniff_ethernet {
126   u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
127   u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
128   u_short ether_type; /* IP? ARP? RARP? etc */
129 };
130
131 /* IP header */
132 struct sniff_ip {
133   u_char ip_vhl; /* version << 4 | header length >> 2 */
134   u_char ip_tos; /* type of service */
135   u_short ip_len; /* total length */
136   u_short ip_id; /* identification */
137   u_short ip_off; /* fragment offset field */
138 #define IP_RF 0x8000    /* reserved fragment flag */
139 #define IP_DF 0x4000    /* dont fragment flag */
140 #define IP_MF 0x2000    /* more fragments flag */
141 #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
142   u_char ip_ttl; /* time to live */
143   u_char ip_p; /* protocol */
144   u_short ip_sum; /* checksum */
145   struct in_addr ip_src, ip_dst; /* source and dest address */
146 };
147 #define IP_OFF(ip)              (((ip)->ip_off) & IP_OFFMASK)
148 #define IP_DF_VAL(ip)           ((((ip)->ip_off) & IP_DF) >> 14)
149 #define IP_MF_VAL(ip)           ((((ip)->ip_off) & IP_MF) >> 13)
150 #define IP_HL(ip)   (((ip)->ip_vhl) & 0x0f)
151 #define IP_V(ip)    (((ip)->ip_vhl) >> 4)
152
153 /* TCP header */
154 typedef u_int tcp_seq;
155
156 struct sniff_tcp {
157   u_short th_sport; /* source port */
158   u_short th_dport; /* destination port */
159   tcp_seq th_seq; /* sequence number */
160   tcp_seq th_ack; /* acknowledgement number */
161   u_char th_offx2; /* data offset, rsvd */
162 #define TH_OFF(th)  (((th)->th_offx2 & 0xf0) >> 4)
163   u_char th_flags;
164 #define TH_FIN 0x01
165 #define TH_SYN 0x02
166 #define TH_RST 0x04
167 #define TH_PUSH 0x08
168 #define TH_ACK 0x10
169 #define TH_URG 0x20
170 #define TH_ECE 0x40
171 #define TH_CWR 0x80
172 #define TH_FLAGS (TH_FIN|TH_SYN|TH_RST|TH_ACK|TH_URG|TH_ECE|TH_CWR)
173   u_short th_win; /* window */
174   u_short th_sum; /* checksum */
175   u_short th_urp; /* urgent pointer */
176 };
177
178 // Payload extraction /////////////////////////////////////////////////////////////////////////////////////
179 u_char *getPayload(const u_char* packet, int packetSize, int &payloadSize,
180                    std::string &srcIp, std::string &dstIp, int &fragmentId, bool &dfFlag,
181                    bool &mfFlag, int &fragmentOffset) {
182   const struct sniff_ip *ip; /* The IP header */
183   const struct sniff_tcp *tcp; /* The TCP header */
184   u_int size_ip;
185   u_int size_tcp;
186   ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);
187   size_ip = IP_HL(ip) * 4; // 4 bytes per 32 bits word
188
189   if(size_ip < 20) {
190     LOGDEBUG(
191       Logger::debug(anna::functions::asString("Invalid IP header length: %d bytes", size_ip), ANNA_FILE_LOCATION));
192     return NULL;
193   }
194
195   static char str[INET_ADDRSTRLEN];
196   inet_ntop(AF_INET, &(ip->ip_src), str, INET_ADDRSTRLEN);
197   srcIp = str;
198   inet_ntop(AF_INET, &(ip->ip_dst), str, INET_ADDRSTRLEN);
199   dstIp = str;
200   LOGDEBUG(
201     Logger::debug(anna::functions::asString("ip_id: %d | ip_off: %d", ip->ip_id, ip->ip_off), ANNA_FILE_LOCATION));
202   fragmentId = ip->ip_id;
203   dfFlag = IP_DF_VAL(ip);
204   mfFlag = IP_MF_VAL(ip);
205   fragmentOffset = IP_OFF(ip);
206   tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip);
207   size_tcp = TH_OFF(tcp) * 4;
208
209   if(size_tcp < 20) {
210     LOGDEBUG(
211       Logger::debug(anna::functions::asString("Invalid TCP header length: %d bytes", size_tcp), ANNA_FILE_LOCATION));
212     return NULL;
213   }
214
215   int payloadOffset = SIZE_ETHERNET + size_ip + size_tcp;
216   LOGDEBUG(
217     Logger::debug(anna::functions::asString("PayloadOffset=%d", payloadOffset), ANNA_FILE_LOCATION));
218   payloadSize = packetSize - payloadOffset;
219   return ((u_char *)(packet + payloadOffset));
220 }
221
222 // Sniffing callback //////////////////////////////////////////////////////////////////////////////////////
223 void my_callback(u_char *useless, const struct pcap_pkthdr* pkthdr,
224                  const u_char* packet) {
225   static int count = 1;
226   static Payload auxPayload;
227   int packetSize = pkthdr->len;
228   int payloadSize;
229   std::string srcIp, dstIp;
230   int fragmentId, fragmentOffset;
231   bool dfFlag, mfFlag;
232   const u_char* payload = getPayload(packet, packetSize, payloadSize, srcIp,
233                                      dstIp, fragmentId, dfFlag, mfFlag, fragmentOffset);
234
235   if(payload && (payloadSize > 0)) {
236     LOGDEBUG(
237       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);
238       Logger::debug(msg, ANNA_FILE_LOCATION););
239     auxPayload.setDiameterLength(
240       (payload[1] << 16) + (payload[2] << 8) + payload[3]);
241     auxPayload.setSourceIP(srcIp);
242     auxPayload.setDestinationIP(dstIp);
243     auxPayload.setTimestamp(pkthdr->ts.tv_sec);
244     auxPayload.setTimestampU(pkthdr->ts.tv_usec);
245     bool completed = auxPayload.appendData((const char *) payload, payloadSize);
246
247     if(completed) {
248       G_payloads[count] = auxPayload;
249       auxPayload.reset();
250     }
251   }
252
253   count++;
254 }
255
256 bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) throw() {
257   // Get hex string
258   static char buffer[8192];
259   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
260
261   if(infile.is_open()) {
262     infile >> buffer;
263     std::string hexString(buffer, strlen(buffer));
264     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
265     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
266     LOGDEBUG(
267       std::string msg = "Hex string (remove colons if exists): ";
268       msg += hexString;
269       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
270     );
271     anna::functions::fromHexString(hexString, db);
272     // Close file
273     infile.close();
274     return true;
275   }
276
277   return false;
278 }
279
280
281 void _exit(const std::string &message, int resultCode = 1) {
282   if(resultCode)
283     std::cerr << message << std::endl << std::endl;
284   else
285     std::cout << message << std::endl << std::endl;
286
287   exit(resultCode);
288 }
289
290
291 //-------------------------------------------------------------------
292 int main(int argc, char **argv) {
293   std::string exec = argv[0];
294   std::string execBN = exec.substr(exec.find_last_of("/") + 1);
295   std::string filetrace = execBN + ".trace";
296   std::cout << std::endl;
297
298   //check command line arguments
299   if(argc < 2) {
300     std::string msg = "Usage: "; msg += exec;
301     msg += " <pcap file> [--write-hex: to write hex files] [--debug: activates debug level traces (warning by default)]\n\n";
302     _exit(msg);
303   }
304
305   // Command-line parameters:
306   std::string inputFile = argv[1];
307   //bool isHex = (inputFile.substr(inputFile.find_last_of(".") + 1) == "hex");
308   std::string outputFile = inputFile; // extension will be added later
309   std::string optionals;
310   int indx = 2;
311   while(indx < argc) { optionals += " "; optionals += argv[indx]; indx++; }
312
313   bool debug = (optionals.find("--debug") != std::string::npos);
314   bool writeHex = (optionals.find("--write-hex") != std::string::npos);
315   Logger::setLevel(debug ? Logger::Debug:Logger::Warning);
316   Logger::initialize(execBN.c_str(), new TraceWriter(filetrace.c_str(), 2048000));
317
318   anna::DataBlock db_aux(true);
319
320   // SNIFFING //////////////////////////////////////////////////////////////////////////////////////////////7
321   //temporary packet buffers
322   //struct pcap_pkthdr header; // The header that pcap gives us
323   //const u_char *packet;      // The actual packet
324   //------------------
325   //open the pcap file
326   pcap_t *handle;
327   char errbuf[PCAP_ERRBUF_SIZE];        //not sure what to do with this, oh well
328   handle = pcap_open_offline(inputFile.c_str(), errbuf); //call pcap library function
329
330   if(handle == NULL) _exit(errbuf, 2);
331
332   // TODO: add filtering. At the moment, pcap must be previously filtered for diameter protocol ('tcp port 3868' or any other filter allowed)
333   /*
334   // Filtering:
335   std::string filter = ?????;
336   struct bpf_program _fp;
337   struct bpf_program *fp = &_fp;
338   bpf_u_int32 netmask = 4294967295; // FFFFFFFF
339
340   if (pcap_compile(handle, fp, (char*)(filter.c_str()), 1, netmask) == -1) {
341         std::cerr << "Couldn't compile the filter " << filter << std::endl;
342     return(2); 
343   }
344
345   if (pcap_setfilter(handle, fp) == -1) {
346     std::cerr << "Couldn't set the filter " << filter << std::endl; 
347     return(2); 
348   }
349   */
350
351   //begin processing the packets in this particular file
352   int packets = -1;
353
354   try {
355     while(packets != 0)
356       packets = pcap_dispatch(handle, -1, (pcap_handler) my_callback, NULL);
357   } catch(RuntimeException &ex) {
358     _exit(ex.asString());
359   }
360
361   pcap_close(handle);  //close the pcap file
362
363   // Print payloads //////////////////////////////////////////////////////////////////////////////////////////////
364   // Open output file:
365   outputFile += ".report";
366   std::ofstream out(outputFile.c_str(), std::ifstream::out);
367
368   for(payloads_it it = G_payloads.begin(); it != G_payloads.end(); it++) {
369     LOGDEBUG(
370       Logger::debug(anna::functions::asString("Dumping frame %d", it->first), ANNA_FILE_LOCATION));
371     time_t ts = (it->second).getTimestamp();
372     int tsu = (it->second).getTimestampU();
373     std::string ts_str = ctime(&ts);
374     ts_str.erase(ts_str.find("\n"));
375     out << "Frame:           " << anna::functions::asString(it->first) << std::endl;
376     out << "Date:            " << ts_str << std::endl;
377     out << "Timestamp:       " << anna::functions::asString((int)ts) << "."
378         << anna::functions::asString((int)tsu) << std::endl;
379     out << "Origin IP:       " << (it->second).getSourceIP() << std::endl;
380     out << "Destination IP:  " << (it->second).getDestinationIP() << std::endl;
381     out << "Destination IP:  " << (it->second).getDestinationIP() << std::endl;
382     out << "Hex String:      " << (it->second).getDataAsHex() << std::endl;
383
384     // Create hex file:
385     if (writeHex) {
386       std::string hexFile =  anna::functions::asString(it->first) + ".hex";
387       std::ofstream hex(hexFile.c_str(), std::ifstream::out);
388       hex << (it->second).getDataAsHex();
389       hex.close();
390     }
391
392     out << std::endl;
393   }
394
395   // Close output file:
396   out.close();
397   std::string msg = "Open '"; msg += filetrace; msg += "' in order to see process traces.\n";
398   msg += "Open '"; msg += outputFile; msg += "' to see decoding results.\n";
399   if (writeHex) msg += "Open '<frame number>.hex' to see specific frame data.";
400   _exit(msg, 0);
401 }
402