]> git.stg.codes - stg.git/blob - stargazer/plugins/capture/cap_nf/cap_nf.cpp
Public interfaces: part 1
[stg.git] / stargazer / plugins / capture / cap_nf / cap_nf.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18 Date: 16.05.2008
19 */
20
21 /*
22 * Author : Maxim Mamontov <faust@stg.dp.ua>
23 */
24
25 /*
26 $Revision: 1.11 $
27 $Date: 2010/09/10 06:41:06 $
28 $Author: faust $
29 */
30
31 #include "cap_nf.h"
32
33 #include "stg/common.h"
34 #include "stg/raw_ip_packet.h"
35 #include "stg/traffcounter.h"
36
37 #include <vector>
38
39 #include <csignal>
40 #include <cerrno>
41 #include <cstring>
42
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47
48 namespace
49 {
50
51 struct NF_HEADER {
52     uint16_t version;   // Protocol version
53     uint16_t count;     // Flows count
54     uint32_t uptime;    // System uptime
55     uint32_t timestamp; // UNIX timestamp
56     uint32_t nsecs;     // Residual nanoseconds
57     uint32_t flowSeq;   // Sequence counter
58     uint8_t  eType;     // Engine type
59     uint8_t  eID;       // Engine ID
60     uint16_t sInterval; // Sampling mode and interval
61 };
62
63 struct NF_DATA {
64     uint32_t srcAddr;   // Flow source address
65     uint32_t dstAddr;   // Flow destination address
66     uint32_t nextHop;   // IP addres on next hop router
67     uint16_t inSNMP;    // SNMP index of input iface
68     uint16_t outSNMP;   // SNMP index of output iface
69     uint32_t packets;   // Packets in flow
70     uint32_t octets;    // Total number of bytes in flow
71     uint32_t timeStart; // Uptime on first packet in flow
72     uint32_t timeFinish;// Uptime on last packet in flow
73     uint16_t srcPort;   // Flow source port
74     uint16_t dstPort;   // Flow destination port
75     uint8_t  pad1;      // 1-byte padding
76     uint8_t  TCPFlags;  // Cumulative OR of TCP flags
77     uint8_t  proto;     // IP protocol type (tcp, udp, etc.)
78     uint8_t  tos;       // IP Type of Service (ToS)
79     uint16_t srcAS;     // Source BGP autonomous system number
80     uint16_t dstAS;     // Destination BGP autonomus system number
81     uint8_t  srcMask;   // Source address mask in "slash" notation
82     uint8_t  dstMask;   // Destination address mask in "slash" notation
83     uint16_t pad2;      // 2-byte padding
84 };
85
86 #define BUF_SIZE (sizeof(NF_HEADER) + 30 * sizeof(NF_DATA))
87
88 }
89
90 extern "C" STG::Plugin* GetPlugin()
91 {
92     static NF_CAP plugin;
93     return &plugin;
94 }
95
96 NF_CAP::NF_CAP()
97     : traffCnt(NULL),
98       runningTCP(false),
99       runningUDP(false),
100       stoppedTCP(true),
101       stoppedUDP(true),
102       portT(0),
103       portU(0),
104       sockTCP(-1),
105       sockUDP(-1),
106       logger(STG::PluginLogger::get("cap_nf"))
107 {
108 }
109
110 int NF_CAP::ParseSettings()
111 {
112 std::vector<STG::ParamValue>::iterator it;
113 for (it = settings.moduleParams.begin(); it != settings.moduleParams.end(); ++it)
114     {
115     if (it->param == "TCPPort" && !it->value.empty())
116         {
117         if (str2x(it->value[0], portT))
118             {
119             errorStr = "Invalid TCPPort value";
120             printfd(__FILE__, "Error: Invalid TCPPort value\n");
121             return -1;
122             }
123         continue;
124         }
125     if (it->param == "UDPPort" && !it->value.empty())
126         {
127         if (str2x(it->value[0], portU))
128             {
129             errorStr = "Invalid UDPPort value";
130             printfd(__FILE__, "Error: Invalid UDPPort value\n");
131             return -1;
132             }
133         continue;
134         }
135     printfd(__FILE__, "'%s' is not a valid module param\n", it->param.c_str());
136     }
137 return 0;
138 }
139
140 int NF_CAP::Start()
141 {
142 if (portU > 0)
143     {
144     if (OpenUDP())
145         {
146         return -1;
147         }
148     runningUDP = true;
149     if (pthread_create(&tidUDP, NULL, RunUDP, this))
150         {
151         runningUDP = false;
152         CloseUDP();
153         errorStr = "Cannot create UDP thread";
154         logger("Cannot create UDP thread.");
155         printfd(__FILE__, "Error: Cannot create UDP thread\n");
156         return -1;
157         }
158     }
159 if (portT > 0)
160     {
161     if (OpenTCP())
162         {
163         return -1;
164         }
165     runningTCP = true;
166     if (pthread_create(&tidTCP, NULL, RunTCP, this))
167         {
168         runningTCP = false;
169         CloseTCP();
170         logger("Cannot create TCP thread.");
171         errorStr = "Cannot create TCP thread";
172         printfd(__FILE__, "Error: Cannot create TCP thread\n");
173         return -1;
174         }
175     }
176 return 0;
177 }
178
179 int NF_CAP::Stop()
180 {
181 runningTCP = runningUDP = false;
182 if (portU && !stoppedUDP)
183     {
184     CloseUDP();
185     for (int i = 0; i < 25 && !stoppedUDP; ++i)
186         {
187         struct timespec ts = {0, 200000000};
188         nanosleep(&ts, NULL);
189         }
190     if (stoppedUDP)
191         {
192         pthread_join(tidUDP, NULL);
193         }
194     else
195         {
196         if (pthread_kill(tidUDP, SIGUSR1))
197             {
198             errorStr = "Error sending signal to UDP thread";
199             logger("Error sending sugnal to UDP thread.");
200             printfd(__FILE__, "Error: Error sending signal to UDP thread\n");
201             return -1;
202             }
203         printfd(__FILE__, "UDP thread NOT stopped\n");
204         logger("Cannot stop UDP thread.");
205         }
206     }
207 if (portT && !stoppedTCP)
208     {
209     CloseTCP();
210     for (int i = 0; i < 25 && !stoppedTCP; ++i)
211         {
212         struct timespec ts = {0, 200000000};
213         nanosleep(&ts, NULL);
214         }
215     if (stoppedTCP)
216         {
217         pthread_join(tidTCP, NULL);
218         }
219     else
220         {
221         if (pthread_kill(tidTCP, SIGUSR1))
222             {
223             errorStr = "Error sending signal to TCP thread";
224             logger("Error sending signal to TCP thread.");
225             printfd(__FILE__, "Error: Error sending signal to TCP thread\n");
226             return -1;
227             }
228         printfd(__FILE__, "TCP thread NOT stopped\n");
229         logger("Cannot stop TCP thread.");
230         }
231     }
232 return 0;
233 }
234
235 bool NF_CAP::OpenUDP()
236 {
237 struct sockaddr_in sin;
238 sockUDP = socket(PF_INET, SOCK_DGRAM, 0);
239 if (sockUDP <= 0)
240     {
241     errorStr = "Error opening UDP socket";
242     logger("Cannot create UDP socket: %s", strerror(errno));
243     printfd(__FILE__, "Error: Error opening UDP socket\n");
244     return true;
245     }
246 sin.sin_family = AF_INET;
247 sin.sin_port = htons(portU);
248 sin.sin_addr.s_addr = inet_addr("0.0.0.0");
249 if (bind(sockUDP, (struct sockaddr *)&sin, sizeof(sin)))
250     {
251     errorStr = "Error binding UDP socket";
252     logger("Cannot bind UDP socket: %s", strerror(errno));
253     printfd(__FILE__, "Error: Error binding UDP socket\n");
254     return true;
255     }
256 return false;
257 }
258
259 bool NF_CAP::OpenTCP()
260 {
261 struct sockaddr_in sin;
262 sockTCP = socket(PF_INET, SOCK_STREAM, 0);
263 if (sockTCP <= 0)
264     {
265     errorStr = "Error opening TCP socket";
266     logger("Cannot create TCP socket: %s", strerror(errno));
267     printfd(__FILE__, "Error: Error opening TCP socket\n");
268     return true;
269     }
270 sin.sin_family = AF_INET;
271 sin.sin_port = htons(portT);
272 sin.sin_addr.s_addr = inet_addr("0.0.0.0");
273 if (bind(sockTCP, (struct sockaddr *)&sin, sizeof(sin)))
274     {
275     errorStr = "Error binding TCP socket";
276     logger("Cannot bind TCP socket: %s", strerror(errno));
277     printfd(__FILE__, "Error: Error binding TCP socket\n");
278     return true;
279     }
280 if (listen(sockTCP, 1))
281     {
282     errorStr = "Error listening on TCP socket";
283     logger("Cannot listen on TCP socket: %s", strerror(errno));
284     printfd(__FILE__, "Error: Error listening TCP socket\n");
285     return true;
286     }
287 return false;
288 }
289
290 void * NF_CAP::RunUDP(void * c)
291 {
292 sigset_t signalSet;
293 sigfillset(&signalSet);
294 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
295
296 NF_CAP * cap = static_cast<NF_CAP *>(c);
297 cap->stoppedUDP = false;
298 while (cap->runningUDP)
299     {
300     if (!WaitPackets(cap->sockUDP))
301         {
302         continue;
303         }
304
305     // Data
306     struct sockaddr_in sin;
307     socklen_t slen = sizeof(sin);
308     uint8_t buf[BUF_SIZE];
309     ssize_t res = recvfrom(cap->sockUDP, buf, BUF_SIZE, 0, reinterpret_cast<struct sockaddr *>(&sin), &slen);
310     if (!cap->runningUDP)
311         break;
312
313     if (res < 0)
314         {
315         cap->logger("recvfrom error: %s", strerror(errno));
316         continue;
317         }
318
319     if (res == 0) // EOF
320         {
321         continue;
322         }
323
324     if (res < 24)
325         {
326         if (errno != EINTR)
327             {
328             cap->errorStr = "Invalid data received";
329             printfd(__FILE__, "Error: Invalid data received through UDP\n");
330             }
331         continue;
332         }
333
334     cap->ParseBuffer(buf, res);
335     }
336 cap->stoppedUDP = true;
337 return NULL;
338 }
339
340 void * NF_CAP::RunTCP(void * c)
341 {
342 sigset_t signalSet;
343 sigfillset(&signalSet);
344 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
345
346 NF_CAP * cap = static_cast<NF_CAP *>(c);
347 cap->stoppedTCP = false;
348 while (cap->runningTCP)
349     {
350     if (!WaitPackets(cap->sockTCP))
351         {
352         continue;
353         }
354
355     // Data
356     struct sockaddr_in sin;
357     socklen_t slen = sizeof(sin);
358     int sd = accept(cap->sockTCP, reinterpret_cast<struct sockaddr *>(&sin), &slen);
359     if (!cap->runningTCP)
360         break;
361
362     if (sd <= 0)
363         {
364         if (sd < 0)
365             cap->logger("accept error: %s", strerror(errno));
366         continue;
367         }
368
369     if (!WaitPackets(sd))
370         {
371         close(sd);
372         continue;
373         }
374
375     uint8_t buf[BUF_SIZE];
376     ssize_t res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
377
378     if (res < 0)
379         cap->logger("recv error: %s", strerror(errno));
380
381     close(sd);
382
383     if (!cap->runningTCP)
384         break;
385
386     if (res == 0) // EOF
387         {
388         continue;
389         }
390
391     // Wrong logic!
392     // Need to check actual data length and wait all data to receive
393     if (res < 24)
394         {
395         continue;
396         }
397
398     cap->ParseBuffer(buf, res);
399     }
400 cap->stoppedTCP = true;
401 return NULL;
402 }
403
404 void NF_CAP::ParseBuffer(uint8_t * buf, ssize_t size)
405 {
406 STG::RawPacket ip;
407 NF_HEADER * hdr = reinterpret_cast<NF_HEADER *>(buf);
408 if (htons(hdr->version) != 5)
409     {
410     return;
411     }
412
413 int packets = htons(hdr->count);
414
415 if (packets < 0 || packets > 30)
416     {
417     return;
418     }
419
420 if (24 + 48 * packets != size)
421     {
422     // See 'wrong logic' upper
423     return;
424     }
425
426 for (int i = 0; i < packets; ++i)
427     {
428     NF_DATA * data = reinterpret_cast<NF_DATA *>(buf + 24 + i * 48);
429
430     ip.rawPacket.header.ipHeader.ip_v = 4;
431     ip.rawPacket.header.ipHeader.ip_hl = 5;
432     ip.rawPacket.header.ipHeader.ip_p = data->proto;
433     ip.dataLen = ntohl(data->octets);
434     ip.rawPacket.header.ipHeader.ip_src.s_addr = data->srcAddr;
435     ip.rawPacket.header.ipHeader.ip_dst.s_addr = data->dstAddr;
436     ip.rawPacket.header.sPort = data->srcPort;
437     ip.rawPacket.header.dPort = data->dstPort;
438
439     traffCnt->process(ip);
440     }
441 }