]> The Tcpdump Group git mirrors - libpcap/blob - rpcapd/daemon.c
aaa54c9e3b885dd375fb6527337865949e707f17
[libpcap] / rpcapd / daemon.c
1 /*
2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the Politecnico di Torino nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35
36 #include "ftmacros.h"
37 #include "varattrs.h"
38
39 #include <errno.h> // for the errno variable
40 #include <stdlib.h> // for malloc(), free(), ...
41 #include <string.h> // for strlen(), ...
42 #include <limits.h> // for INT_MAX
43
44 #ifdef _WIN32
45 #include <process.h> // for threads
46 #else
47 #include <unistd.h>
48 #include <pthread.h>
49 #include <signal.h>
50 #include <sys/time.h>
51 #include <sys/types.h> // for select() and such
52 #include <pwd.h> // for password management
53 #endif
54
55 #ifdef HAVE_GETSPNAM
56 #include <shadow.h> // for password management
57 #endif
58
59 #include <pcap.h> // for libpcap/WinPcap calls
60
61 #include "fmtutils.h"
62 #include "sockutils.h" // for socket calls
63 #include "portability.h"
64 #include "rpcap-protocol.h"
65 #include "daemon.h"
66 #include "log.h"
67
68 #ifdef HAVE_OPENSSL
69 #include <openssl/ssl.h>
70 #include "sslutils.h"
71 #endif
72
73 //
74 // Timeout, in seconds, when we're waiting for a client to send us an
75 // authentication request; if they don't send us a request within that
76 // interval, we drop the connection, so we don't stay stuck forever.
77 //
78 #define RPCAP_TIMEOUT_INIT 90
79
80 //
81 // Timeout, in seconds, when we're waiting for an authenticated client
82 // to send us a request, if a capture isn't in progress; if they don't
83 // send us a request within that interval, we drop the connection, so
84 // we don't stay stuck forever.
85 //
86 #define RPCAP_TIMEOUT_RUNTIME 180
87
88 //
89 // Time, in seconds, that we wait after a failed authentication attempt
90 // before processing the next request; this prevents a client from
91 // rapidly trying different accounts or passwords.
92 //
93 #define RPCAP_SUSPEND_WRONGAUTH 1
94
95 // Parameters for the service loop.
96 struct daemon_slpars
97 {
98 SOCKET sockctrl; //!< SOCKET ID of the control connection
99 SSL *ssl; //!< Optional SSL handler for the controlling sockets
100 int isactive; //!< Not null if the daemon has to run in active mode
101 int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
102 };
103
104 //
105 // Data for a session managed by a thread.
106 // It includes both a Boolean indicating whether we *have* a thread,
107 // and a platform-dependent (UN*X vs. Windows) identifier for the
108 // thread; on Windows, we could use an invalid handle to indicate
109 // that we don't have a thread, but there *is* no portable "no thread"
110 // value for a pthread_t on UN*X.
111 //
112 struct session {
113 SOCKET sockctrl;
114 SOCKET sockdata;
115 SSL *ctrl_ssl, *data_ssl; // optional SSL handlers for sockctrl and sockdata.
116 uint8 protocol_version;
117 pcap_t *fp;
118 unsigned int TotCapt;
119 int have_thread;
120 #ifdef _WIN32
121 HANDLE thread;
122 #else
123 pthread_t thread;
124 #endif
125 };
126
127 // Locally defined functions
128 static int daemon_msg_err(SOCKET sockctrl, SSL *, uint32 plen);
129 static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
130 static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
131
132 static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars,
133 uint32 plen);
134
135 static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars,
136 uint32 plen, char *source, size_t sourcelen);
137 static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars,
138 uint32 plen, char *source, struct session **sessionp,
139 struct rpcap_sampling *samp_param, int uses_ssl);
140 static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
141 struct session *session);
142
143 static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
144 struct session *session, uint32 plen);
145 static int daemon_unpackapplyfilter(SOCKET sockctrl, SSL *, struct session *session, uint32 *plenp, char *errbuf);
146
147 static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
148 struct session *session, uint32 plen, struct pcap_stat *stats,
149 unsigned int svrcapt);
150
151 static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars,
152 uint32 plen, struct rpcap_sampling *samp_param);
153
154 static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
155 #ifdef _WIN32
156 static unsigned __stdcall daemon_thrdatamain(void *ptr);
157 #else
158 static void *daemon_thrdatamain(void *ptr);
159 static void noop_handler(int sign);
160 #endif
161
162 static int rpcapd_recv_msg_header(SOCKET sock, SSL *, struct rpcap_header *headerp);
163 static int rpcapd_recv(SOCKET sock, SSL *, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
164 static int rpcapd_discard(SOCKET sock, SSL *, uint32 len);
165 static void session_close(struct session *);
166
167 //
168 // TLS record layer header; used when processing the first message from
169 // the client, in case we aren't doing TLS but they are.
170 //
171 struct tls_record_header {
172 uint8 type; // ContentType - will be 22, for Handshake
173 uint8 version_major; // TLS protocol major version
174 uint8 version_injor; // TLS protocol minor version
175 // This is *not* aligned on a 2-byte boundary; we just
176 // declare it as two bytes. Don't assume any particular
177 // compiler's mechanism for saying "packed"!
178 uint8 length_hi; // Upper 8 bits of payload length
179 uint8 length_lo; // Low 8 bits of payload length
180 };
181
182 #define TLS_RECORD_HEADER_LEN 5 // Don't use sizeof in case it's padded
183
184 #define TLS_RECORD_TYPE_ALERT 21
185 #define TLS_RECORD_TYPE_HANDSHAKE 22
186
187 //
188 // TLS alert message.
189 //
190 struct tls_alert {
191 uint8 alert_level;
192 uint8 alert_description;
193 };
194
195 #define TLS_ALERT_LEN 2
196
197 #define TLS_ALERT_LEVEL_FATAL 2
198 #define TLS_ALERT_HANDSHAKE_FAILURE 40
199
200 int
201 daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients,
202 int nullAuthAllowed, int uses_ssl)
203 {
204 uint8 first_octet;
205 struct tls_record_header tls_header;
206 struct tls_alert tls_alert;
207 struct daemon_slpars pars; // service loop parameters
208 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
209 char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
210 int host_port_check_status;
211 SSL *ssl = NULL;
212 int nrecv;
213 struct rpcap_header header; // RPCAP message general header
214 uint32 plen; // payload length from header
215 int authenticated = 0; // 1 if the client has successfully authenticated
216 char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
217 int got_source = 0; // 1 if we've gotten the source from an open request
218 #ifndef _WIN32
219 struct sigaction action;
220 #endif
221 struct session *session = NULL; // struct session main variable
222 const char *msg_type_string; // string for message type
223 int client_told_us_to_close = 0; // 1 if the client told us to close the capture
224
225 // needed to save the values of the statistics
226 struct pcap_stat stats;
227 unsigned int svrcapt;
228
229 struct rpcap_sampling samp_param; // in case sampling has been requested
230
231 // Structures needed for the select() call
232 fd_set rfds; // set of socket descriptors we have to check
233 struct timeval tv; // maximum time the select() can block waiting for data
234 int retval; // select() return value
235
236 *errbuf = 0; // Initialize errbuf
237
238 //
239 // Peek into the socket to determine whether the client sent us
240 // a TLS handshake message or a non-TLS rpcapd message.
241 //
242 // The first byte of an rpcapd request is the version number;
243 // the first byte of a TLS handshake message is 22. The
244 // first request to an rpcapd server must be an authentication
245 // request or a close request, and must have a version number
246 // of 0, so it will be possible to distinguish between an
247 // initial plaintext request to a server and an initial TLS
248 // handshake message.
249 //
250 nrecv = sock_recv(sockctrl, NULL, (char *)&first_octet, 1,
251 SOCK_EOF_ISNT_ERROR|SOCK_MSG_PEEK, errbuf, PCAP_ERRBUF_SIZE);
252 if (nrecv == -1)
253 {
254 // Fatal error.
255 rpcapd_log(LOGPRIO_ERROR, "Peek from client failed: %s", errbuf);
256 goto end;
257 }
258 if (nrecv == 0)
259 {
260 // Client closed the connection.
261 goto end;
262 }
263
264 #ifdef HAVE_OPENSSL
265 //
266 // We have to upgrade to TLS as soon as possible, so that the
267 // whole protocol goes through the encrypted tunnel, including
268 // early error messages.
269 //
270 // Even in active mode, the other end has to initiate the TLS
271 // handshake as we still are the server as far as TLS is concerned,
272 // so we don't check isactive.
273 //
274 if (uses_ssl)
275 {
276 //
277 // We're expecting a TLS handshake message. If this
278 // isn't one, assume it's a non-TLS rpcapd message.
279 //
280 // The first octet of a TLS handshake is
281 // TLS_RECORD_TYPE_HANDSHAKE.
282 //
283 if (first_octet != TLS_RECORD_TYPE_HANDSHAKE)
284 {
285 //
286 // We assume this is a non-TLS rpcapd message.
287 //
288 // Read the message header from the client.
289 //
290 nrecv = rpcapd_recv_msg_header(sockctrl, NULL, &header);
291 if (nrecv == -1)
292 {
293 // Fatal error.
294 goto end;
295 }
296 if (nrecv == -2)
297 {
298 // Client closed the connection.
299 goto end;
300 }
301 plen = header.plen;
302
303 // Discard the rest of the message.
304 if (rpcapd_discard(sockctrl, NULL, plen) == -1)
305 {
306 // Network error.
307 goto end;
308 }
309
310 //
311 // Send an authentication error, indicating
312 // that we require TLS.
313 //
314 if (rpcap_senderror(sockctrl, NULL, header.ver,
315 PCAP_ERR_TLS_REQUIRED,
316 "TLS is required by this server", errbuf) == -1)
317 {
318 // That failed; log a message and give up.
319 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
320 goto end;
321 }
322
323 // Shut the session down.
324 goto end;
325 }
326 ssl = ssl_promotion(1, sockctrl, errbuf, PCAP_ERRBUF_SIZE);
327 if (! ssl)
328 {
329 rpcapd_log(LOGPRIO_ERROR, "TLS handshake on control connection failed: %s",
330 errbuf);
331 goto end;
332 }
333 }
334 else
335 #endif
336 {
337 //
338 // We're expecting a non-TLS rpcapd message. If this
339 // looks, instead, like a TLS handshake message, send
340 // a TLS handshake_failed alert.
341 //
342 // The first octet of a TLS handshake is
343 // TLS_RECORD_TYPE_HANDSHAKE.
344 //
345 if (first_octet == TLS_RECORD_TYPE_HANDSHAKE)
346 {
347 //
348 // TLS handshake.
349 // Read the record header.
350 //
351 nrecv = sock_recv(sockctrl, ssl, (char *) &tls_header,
352 sizeof tls_header, SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR,
353 errbuf, PCAP_ERRBUF_SIZE);
354 if (nrecv == -1)
355 {
356 // Network error.
357 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
358 goto end;
359 }
360 if (nrecv == 0)
361 {
362 // Immediate EOF
363 goto end;
364 }
365 plen = (tls_header.length_hi << 8) | tls_header.length_lo;
366
367 // Discard the rest of the message.
368 if (rpcapd_discard(sockctrl, NULL, plen) == -1)
369 {
370 // Network error.
371 goto end;
372 }
373
374 //
375 // Send a TLS handshake failure alert.
376 // Use the same version the client sent us.
377 //
378 tls_header.type = TLS_RECORD_TYPE_ALERT;
379 tls_header.length_hi = 0;
380 tls_header.length_lo = TLS_ALERT_LEN;
381
382 if (sock_send(sockctrl, NULL, (char *) &tls_header,
383 TLS_RECORD_HEADER_LEN, errbuf, PCAP_ERRBUF_SIZE) == -1)
384 {
385 // That failed; log a messsage and give up.
386 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
387 goto end;
388 }
389
390 tls_alert.alert_level = TLS_ALERT_LEVEL_FATAL;
391 tls_alert.alert_description = TLS_ALERT_HANDSHAKE_FAILURE;
392 if (sock_send(sockctrl, NULL, (char *) &tls_alert,
393 TLS_ALERT_LEN, errbuf, PCAP_ERRBUF_SIZE) == -1)
394 {
395 // That failed; log a messsage and give up.
396 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
397 goto end;
398 }
399 //
400 // Give up anyway.
401 //
402 goto end;
403 }
404 }
405
406 // Set parameters structure
407 pars.sockctrl = sockctrl;
408 pars.ssl = ssl;
409 pars.isactive = isactive; // active mode
410 pars.nullAuthAllowed = nullAuthAllowed;
411
412 //
413 // We have a connection.
414 //
415 // If it's a passive mode connection, check whether the connecting
416 // host is among the ones allowed.
417 //
418 // In either case, we were handed a copy of the host list; free it
419 // as soon as we're done with it.
420 //
421 if (pars.isactive)
422 {
423 // Nothing to do.
424 free(passiveClients);
425 passiveClients = NULL;
426 }
427 else
428 {
429 struct sockaddr_storage from;
430 socklen_t fromlen;
431
432 //
433 // Get the address of the other end of the connection.
434 //
435 fromlen = sizeof(struct sockaddr_storage);
436 if (getpeername(pars.sockctrl, (struct sockaddr *)&from,
437 &fromlen) == -1)
438 {
439 sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
440 if (rpcap_senderror(pars.sockctrl, pars.ssl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
441 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
442 goto end;
443 }
444
445 //
446 // Are they in the list of host/port combinations we allow?
447 //
448 host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE);
449 free(passiveClients);
450 passiveClients = NULL;
451 if (host_port_check_status < 0)
452 {
453 if (host_port_check_status == -2) {
454 //
455 // We got an error; log it.
456 //
457 rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf);
458 }
459
460 //
461 // Sorry, we can't let you in.
462 //
463 if (rpcap_senderror(pars.sockctrl, pars.ssl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
464 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
465 goto end;
466 }
467 }
468
469 #ifndef _WIN32
470 //
471 // Catch SIGUSR1, but do nothing. We use it to interrupt the
472 // capture thread to break it out of a loop in which it's
473 // blocked waiting for packets to arrive.
474 //
475 // We don't want interrupted system calls to restart, so that
476 // the read routine for the pcap_t gets EINTR rather than
477 // restarting if it's blocked in a system call.
478 //
479 memset(&action, 0, sizeof (action));
480 action.sa_handler = noop_handler;
481 action.sa_flags = 0;
482 sigemptyset(&action.sa_mask);
483 sigaction(SIGUSR1, &action, NULL);
484 #endif
485
486 //
487 // The client must first authenticate; loop until they send us a
488 // message with a version we support and credentials we accept,
489 // they send us a close message indicating that they're giving up,
490 // or we get a network error or other fatal error.
491 //
492 while (!authenticated)
493 {
494 //
495 // If we're not in active mode, we use select(), with a
496 // timeout, to wait for an authentication request; if
497 // the timeout expires, we drop the connection, so that
498 // a client can't just connect to us and leave us
499 // waiting forever.
500 //
501 if (!pars.isactive)
502 {
503 FD_ZERO(&rfds);
504 // We do not have to block here
505 tv.tv_sec = RPCAP_TIMEOUT_INIT;
506 tv.tv_usec = 0;
507
508 FD_SET(pars.sockctrl, &rfds);
509
510 retval = select((int)pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
511 if (retval == -1)
512 {
513 sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
514 if (rpcap_senderror(pars.sockctrl, pars.ssl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
515 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
516 goto end;
517 }
518
519 // The timeout has expired
520 // So, this was a fake connection. Drop it down
521 if (retval == 0)
522 {
523 if (rpcap_senderror(pars.sockctrl, pars.ssl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
524 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
525 goto end;
526 }
527 }
528
529 //
530 // Read the message header from the client.
531 //
532 nrecv = rpcapd_recv_msg_header(pars.sockctrl, pars.ssl, &header);
533 if (nrecv == -1)
534 {
535 // Fatal error.
536 goto end;
537 }
538 if (nrecv == -2)
539 {
540 // Client closed the connection.
541 goto end;
542 }
543
544 plen = header.plen;
545
546 //
547 // While we're in the authentication pharse, all requests
548 // must use version 0.
549 //
550 if (header.ver != 0)
551 {
552 //
553 // Send it back to them with their version.
554 //
555 if (rpcap_senderror(pars.sockctrl, pars.ssl, header.ver,
556 PCAP_ERR_WRONGVER,
557 "RPCAP version in requests in the authentication phase must be 0",
558 errbuf) == -1)
559 {
560 // That failed; log a message and give up.
561 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
562 goto end;
563 }
564
565 // Discard the rest of the message and drop the
566 // connection.
567 (void)rpcapd_discard(pars.sockctrl, pars.ssl, plen);
568 goto end;
569 }
570
571 switch (header.type)
572 {
573 case RPCAP_MSG_AUTH_REQ:
574 retval = daemon_msg_auth_req(&pars, plen);
575 if (retval == -1)
576 {
577 // Fatal error; a message has
578 // been logged, so just give up.
579 goto end;
580 }
581 if (retval == -2)
582 {
583 // Non-fatal error; we sent back
584 // an error message, so let them
585 // try again.
586 continue;
587 }
588
589 // OK, we're authenticated; we sent back
590 // a reply, so start serving requests.
591 authenticated = 1;
592 break;
593
594 case RPCAP_MSG_CLOSE:
595 //
596 // The client is giving up.
597 // Discard the rest of the message, if
598 // there is anything more.
599 //
600 (void)rpcapd_discard(pars.sockctrl, pars.ssl, plen);
601 // We're done with this client.
602 goto end;
603
604 case RPCAP_MSG_ERROR:
605 // Log this and close the connection?
606 // XXX - is this what happens in active
607 // mode, where *we* initiate the
608 // connection, and the client gives us
609 // an error message rather than a "let
610 // me log in" message, indicating that
611 // we're not allowed to connect to them?
612 (void)daemon_msg_err(pars.sockctrl, pars.ssl, plen);
613 goto end;
614
615 case RPCAP_MSG_FINDALLIF_REQ:
616 case RPCAP_MSG_OPEN_REQ:
617 case RPCAP_MSG_STARTCAP_REQ:
618 case RPCAP_MSG_UPDATEFILTER_REQ:
619 case RPCAP_MSG_STATS_REQ:
620 case RPCAP_MSG_ENDCAP_REQ:
621 case RPCAP_MSG_SETSAMPLING_REQ:
622 //
623 // These requests can't be sent until
624 // the client is authenticated.
625 //
626 msg_type_string = rpcap_msg_type_string(header.type);
627 if (msg_type_string != NULL)
628 {
629 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
630 }
631 else
632 {
633 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
634 }
635 if (rpcap_senderror(pars.sockctrl, pars.ssl,
636 header.ver, PCAP_ERR_WRONGMSG,
637 errmsgbuf, errbuf) == -1)
638 {
639 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
640 goto end;
641 }
642 // Discard the rest of the message.
643 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
644 {
645 // Network error.
646 goto end;
647 }
648 break;
649
650 case RPCAP_MSG_PACKET:
651 case RPCAP_MSG_FINDALLIF_REPLY:
652 case RPCAP_MSG_OPEN_REPLY:
653 case RPCAP_MSG_STARTCAP_REPLY:
654 case RPCAP_MSG_UPDATEFILTER_REPLY:
655 case RPCAP_MSG_AUTH_REPLY:
656 case RPCAP_MSG_STATS_REPLY:
657 case RPCAP_MSG_ENDCAP_REPLY:
658 case RPCAP_MSG_SETSAMPLING_REPLY:
659 //
660 // These are server-to-client messages.
661 //
662 msg_type_string = rpcap_msg_type_string(header.type);
663 if (msg_type_string != NULL)
664 {
665 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
666 }
667 else
668 {
669 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
670 }
671 if (rpcap_senderror(pars.sockctrl, pars.ssl,
672 header.ver, PCAP_ERR_WRONGMSG,
673 errmsgbuf, errbuf) == -1)
674 {
675 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
676 goto end;
677 }
678 // Discard the rest of the message.
679 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
680 {
681 // Fatal error.
682 goto end;
683 }
684 break;
685
686 default:
687 //
688 // Unknown message type.
689 //
690 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
691 if (rpcap_senderror(pars.sockctrl, pars.ssl,
692 header.ver, PCAP_ERR_WRONGMSG,
693 errmsgbuf, errbuf) == -1)
694 {
695 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
696 goto end;
697 }
698 // Discard the rest of the message.
699 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
700 {
701 // Fatal error.
702 goto end;
703 }
704 break;
705 }
706 }
707
708 //
709 // OK, the client has authenticated itself, and we can start
710 // processing regular requests from it.
711 //
712
713 //
714 // We don't have any statistics yet.
715 //
716 stats.ps_ifdrop = 0;
717 stats.ps_recv = 0;
718 stats.ps_drop = 0;
719 svrcapt = 0;
720
721 //
722 // Service requests.
723 //
724 for (;;)
725 {
726 errbuf[0] = 0; // clear errbuf
727
728 // Avoid zombies connections; check if the connection is opens but no commands are performed
729 // from more than RPCAP_TIMEOUT_RUNTIME
730 // Conditions:
731 // - I have to be in normal mode (no active mode)
732 // - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
733 // - if the device is closed, I have always to check if a new command arrives
734 //
735 // Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
736 // sockdata is 0
737 if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
738 {
739 // Check for the initial timeout
740 FD_ZERO(&rfds);
741 // We do not have to block here
742 tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
743 tv.tv_usec = 0;
744
745 FD_SET(pars.sockctrl, &rfds);
746
747 retval = select((int)pars.sockctrl + 1, &rfds, NULL, NULL, &tv);
748 if (retval == -1)
749 {
750 sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE);
751 if (rpcap_senderror(pars.sockctrl, pars.ssl,
752 0, PCAP_ERR_NETW,
753 errmsgbuf, errbuf) == -1)
754 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
755 goto end;
756 }
757
758 // The timeout has expired
759 // So, this was a fake connection. Drop it down
760 if (retval == 0)
761 {
762 if (rpcap_senderror(pars.sockctrl, pars.ssl,
763 0, PCAP_ERR_INITTIMEOUT,
764 "The RPCAP initial timeout has expired",
765 errbuf) == -1)
766 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
767 goto end;
768 }
769 }
770
771 //
772 // Read the message header from the client.
773 //
774 nrecv = rpcapd_recv_msg_header(pars.sockctrl, pars.ssl, &header);
775 if (nrecv == -1)
776 {
777 // Fatal error.
778 goto end;
779 }
780 if (nrecv == -2)
781 {
782 // Client closed the connection.
783 goto end;
784 }
785
786 plen = header.plen;
787
788 //
789 // Did the client specify a protocol version that we
790 // support?
791 //
792 if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
793 {
794 //
795 // Tell them it's not a supported version.
796 // Send the error message with their version,
797 // so they don't reject it as having the wrong
798 // version.
799 //
800 if (rpcap_senderror(pars.sockctrl, pars.ssl,
801 header.ver, PCAP_ERR_WRONGVER,
802 "RPCAP version in message isn't supported by the server",
803 errbuf) == -1)
804 {
805 // That failed; log a message and give up.
806 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
807 goto end;
808 }
809
810 // Discard the rest of the message.
811 (void)rpcapd_discard(pars.sockctrl, pars.ssl, plen);
812 // Give up on them.
813 goto end;
814 }
815
816 switch (header.type)
817 {
818 case RPCAP_MSG_ERROR: // The other endpoint reported an error
819 {
820 (void)daemon_msg_err(pars.sockctrl, pars.ssl, plen);
821 // Do nothing; just exit; the error code is already into the errbuf
822 // XXX - actually exit....
823 break;
824 }
825
826 case RPCAP_MSG_FINDALLIF_REQ:
827 {
828 if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1)
829 {
830 // Fatal error; a message has
831 // been logged, so just give up.
832 goto end;
833 }
834 break;
835 }
836
837 case RPCAP_MSG_OPEN_REQ:
838 {
839 //
840 // Process the open request, and keep
841 // the source from it, for use later
842 // when the capture is started.
843 //
844 // XXX - we don't care if the client sends
845 // us multiple open requests, the last
846 // one wins.
847 //
848 retval = daemon_msg_open_req(header.ver, &pars,
849 plen, source, sizeof(source));
850 if (retval == -1)
851 {
852 // Fatal error; a message has
853 // been logged, so just give up.
854 goto end;
855 }
856 got_source = 1;
857 break;
858 }
859
860 case RPCAP_MSG_STARTCAP_REQ:
861 {
862 if (!got_source)
863 {
864 // They never told us what device
865 // to capture on!
866 if (rpcap_senderror(pars.sockctrl, pars.ssl,
867 header.ver,
868 PCAP_ERR_STARTCAPTURE,
869 "No capture device was specified",
870 errbuf) == -1)
871 {
872 // Fatal error; log an
873 // error and give up.
874 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
875 goto end;
876 }
877 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
878 {
879 goto end;
880 }
881 break;
882 }
883
884 if (daemon_msg_startcap_req(header.ver, &pars,
885 plen, source, &session, &samp_param,
886 uses_ssl) == -1)
887 {
888 // Fatal error; a message has
889 // been logged, so just give up.
890 goto end;
891 }
892 break;
893 }
894
895 case RPCAP_MSG_UPDATEFILTER_REQ:
896 {
897 if (session)
898 {
899 if (daemon_msg_updatefilter_req(header.ver,
900 &pars, session, plen) == -1)
901 {
902 // Fatal error; a message has
903 // been logged, so just give up.
904 goto end;
905 }
906 }
907 else
908 {
909 if (rpcap_senderror(pars.sockctrl, pars.ssl,
910 header.ver,
911 PCAP_ERR_UPDATEFILTER,
912 "Device not opened. Cannot update filter",
913 errbuf) == -1)
914 {
915 // That failed; log a message and give up.
916 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
917 goto end;
918 }
919 }
920 break;
921 }
922
923 case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
924 {
925 //
926 // Indicate to our caller that the client
927 // closed the control connection.
928 // This is used only in case of active mode.
929 //
930 client_told_us_to_close = 1;
931 rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
932 goto end;
933 }
934
935 case RPCAP_MSG_STATS_REQ:
936 {
937 if (daemon_msg_stats_req(header.ver, &pars,
938 session, plen, &stats, svrcapt) == -1)
939 {
940 // Fatal error; a message has
941 // been logged, so just give up.
942 goto end;
943 }
944 break;
945 }
946
947 case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
948 {
949 if (session)
950 {
951 // Save statistics (we can need them in the future)
952 if (pcap_stats(session->fp, &stats))
953 {
954 svrcapt = session->TotCapt;
955 }
956 else
957 {
958 stats.ps_ifdrop = 0;
959 stats.ps_recv = 0;
960 stats.ps_drop = 0;
961 svrcapt = 0;
962 }
963
964 if (daemon_msg_endcap_req(header.ver,
965 &pars, session) == -1)
966 {
967 free(session);
968 session = NULL;
969 // Fatal error; a message has
970 // been logged, so just give up.
971 goto end;
972 }
973 free(session);
974 session = NULL;
975 }
976 else
977 {
978 rpcap_senderror(pars.sockctrl, pars.ssl,
979 header.ver,
980 PCAP_ERR_ENDCAPTURE,
981 "Device not opened. Cannot close the capture",
982 errbuf);
983 }
984 break;
985 }
986
987 case RPCAP_MSG_SETSAMPLING_REQ:
988 {
989 if (daemon_msg_setsampling_req(header.ver,
990 &pars, plen, &samp_param) == -1)
991 {
992 // Fatal error; a message has
993 // been logged, so just give up.
994 goto end;
995 }
996 break;
997 }
998
999 case RPCAP_MSG_AUTH_REQ:
1000 {
1001 //
1002 // We're already authenticated; you don't
1003 // get to reauthenticate.
1004 //
1005 rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
1006 if (rpcap_senderror(pars.sockctrl, pars.ssl,
1007 header.ver,
1008 PCAP_ERR_WRONGMSG,
1009 "RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
1010 errbuf) == -1)
1011 {
1012 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1013 goto end;
1014 }
1015 // Discard the rest of the message.
1016 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
1017 {
1018 // Fatal error.
1019 goto end;
1020 }
1021 goto end;
1022
1023 case RPCAP_MSG_PACKET:
1024 case RPCAP_MSG_FINDALLIF_REPLY:
1025 case RPCAP_MSG_OPEN_REPLY:
1026 case RPCAP_MSG_STARTCAP_REPLY:
1027 case RPCAP_MSG_UPDATEFILTER_REPLY:
1028 case RPCAP_MSG_AUTH_REPLY:
1029 case RPCAP_MSG_STATS_REPLY:
1030 case RPCAP_MSG_ENDCAP_REPLY:
1031 case RPCAP_MSG_SETSAMPLING_REPLY:
1032 //
1033 // These are server-to-client messages.
1034 //
1035 msg_type_string = rpcap_msg_type_string(header.type);
1036 if (msg_type_string != NULL)
1037 {
1038 rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
1039 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
1040 }
1041 else
1042 {
1043 rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
1044 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
1045 }
1046 if (rpcap_senderror(pars.sockctrl, pars.ssl,
1047 header.ver, PCAP_ERR_WRONGMSG,
1048 errmsgbuf, errbuf) == -1)
1049 {
1050 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1051 goto end;
1052 }
1053 // Discard the rest of the message.
1054 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
1055 {
1056 // Fatal error.
1057 goto end;
1058 }
1059 goto end;
1060
1061 default:
1062 //
1063 // Unknown message type.
1064 //
1065 rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
1066 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
1067 if (rpcap_senderror(pars.sockctrl, pars.ssl,
1068 header.ver, PCAP_ERR_WRONGMSG,
1069 errbuf, errmsgbuf) == -1)
1070 {
1071 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1072 goto end;
1073 }
1074 // Discard the rest of the message.
1075 if (rpcapd_discard(pars.sockctrl, pars.ssl, plen) == -1)
1076 {
1077 // Fatal error.
1078 goto end;
1079 }
1080 goto end;
1081 }
1082 }
1083 }
1084
1085 end:
1086 // The service loop is finishing up.
1087 // If we have a capture session running, close it.
1088 if (session)
1089 {
1090 session_close(session);
1091 free(session);
1092 session = NULL;
1093 }
1094
1095 //
1096 // Finish using the SSL handle for the control socket, if we
1097 // have an SSL connection, and close the control socket.
1098 //
1099 #ifdef HAVE_OPENSSL
1100 if (ssl)
1101 {
1102 // Finish using the SSL handle for the socket.
1103 // This must be done *before* the socket is closed.
1104 ssl_finish(ssl);
1105 }
1106 #endif
1107 sock_close(sockctrl, NULL, 0);
1108
1109 // Print message and return
1110 rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
1111
1112 return client_told_us_to_close;
1113 }
1114
1115 /*
1116 * This handles the RPCAP_MSG_ERR message.
1117 */
1118 static int
1119 daemon_msg_err(SOCKET sockctrl, SSL *ssl, uint32 plen)
1120 {
1121 char errbuf[PCAP_ERRBUF_SIZE];
1122 char remote_errbuf[PCAP_ERRBUF_SIZE];
1123
1124 if (plen >= PCAP_ERRBUF_SIZE)
1125 {
1126 /*
1127 * Message is too long; just read as much of it as we
1128 * can into the buffer provided, and discard the rest.
1129 */
1130 if (sock_recv(sockctrl, ssl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
1131 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
1132 PCAP_ERRBUF_SIZE) == -1)
1133 {
1134 // Network error.
1135 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1136 return -1;
1137 }
1138 if (rpcapd_discard(sockctrl, ssl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
1139 {
1140 // Network error.
1141 return -1;
1142 }
1143
1144 /*
1145 * Null-terminate it.
1146 */
1147 remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
1148 }
1149 else if (plen == 0)
1150 {
1151 /* Empty error string. */
1152 remote_errbuf[0] = '\0';
1153 }
1154 else
1155 {
1156 if (sock_recv(sockctrl, ssl, remote_errbuf, plen,
1157 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
1158 PCAP_ERRBUF_SIZE) == -1)
1159 {
1160 // Network error.
1161 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1162 return -1;
1163 }
1164
1165 /*
1166 * Null-terminate it.
1167 */
1168 remote_errbuf[plen] = '\0';
1169 }
1170 // Log the message
1171 rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
1172 return 0;
1173 }
1174
1175 /*
1176 * This handles the RPCAP_MSG_AUTH_REQ message.
1177 * It checks if the authentication credentials supplied by the user are valid.
1178 *
1179 * This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
1180 * message in its authentication loop. It reads the body of the
1181 * authentication message from the network and checks whether the
1182 * credentials are valid.
1183 *
1184 * \param sockctrl: the socket for the control connection.
1185 *
1186 * \param nullAuthAllowed: '1' if the NULL authentication is allowed.
1187 *
1188 * \param errbuf: a user-allocated buffer in which the error message
1189 * (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
1190 * bytes long.
1191 *
1192 * \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
1193 * or '-2' if the authentication failed. For errors, an error message is
1194 * returned in the 'errbuf' variable; this gives a message for the
1195 * unrecoverable error or for the authentication failure.
1196 */
1197 static int
1198 daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
1199 {
1200 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1201 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1202 int status;
1203 struct rpcap_auth auth; // RPCAP authentication header
1204 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1205 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1206 struct rpcap_authreply *authreply; // authentication reply message
1207
1208 status = rpcapd_recv(pars->sockctrl, pars->ssl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
1209 if (status == -1)
1210 {
1211 return -1;
1212 }
1213 if (status == -2)
1214 {
1215 goto error;
1216 }
1217
1218 switch (ntohs(auth.type))
1219 {
1220 case RPCAP_RMTAUTH_NULL:
1221 {
1222 if (!pars->nullAuthAllowed)
1223 {
1224 // Send the client an error reply.
1225 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
1226 "Authentication failed; NULL authentication not permitted.");
1227 if (rpcap_senderror(pars->sockctrl, pars->ssl,
1228 0, PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
1229 {
1230 // That failed; log a message and give up.
1231 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1232 return -1;
1233 }
1234 goto error_noreply;
1235 }
1236 break;
1237 }
1238
1239 case RPCAP_RMTAUTH_PWD:
1240 {
1241 char *username, *passwd;
1242 uint32 usernamelen, passwdlen;
1243
1244 usernamelen = ntohs(auth.slen1);
1245 username = (char *) malloc (usernamelen + 1);
1246 if (username == NULL)
1247 {
1248 pcap_fmt_errmsg_for_errno(errmsgbuf,
1249 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
1250 goto error;
1251 }
1252 status = rpcapd_recv(pars->sockctrl, pars->ssl, username, usernamelen, &plen, errmsgbuf);
1253 if (status == -1)
1254 {
1255 free(username);
1256 return -1;
1257 }
1258 if (status == -2)
1259 {
1260 free(username);
1261 goto error;
1262 }
1263 username[usernamelen] = '\0';
1264
1265 passwdlen = ntohs(auth.slen2);
1266 passwd = (char *) malloc (passwdlen + 1);
1267 if (passwd == NULL)
1268 {
1269 pcap_fmt_errmsg_for_errno(errmsgbuf,
1270 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
1271 free(username);
1272 goto error;
1273 }
1274 status = rpcapd_recv(pars->sockctrl, pars->ssl, passwd, passwdlen, &plen, errmsgbuf);
1275 if (status == -1)
1276 {
1277 free(username);
1278 free(passwd);
1279 return -1;
1280 }
1281 if (status == -2)
1282 {
1283 free(username);
1284 free(passwd);
1285 goto error;
1286 }
1287 passwd[passwdlen] = '\0';
1288
1289 if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
1290 {
1291 //
1292 // Authentication failed. Let the client
1293 // know.
1294 //
1295 free(username);
1296 free(passwd);
1297 if (rpcap_senderror(pars->sockctrl, pars->ssl,
1298 0, PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1)
1299 {
1300 // That failed; log a message and give up.
1301 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1302 return -1;
1303 }
1304
1305 //
1306 // Suspend for 1 second, so that they can't
1307 // hammer us with repeated tries with an
1308 // attack such as a dictionary attack.
1309 //
1310 // WARNING: this delay is inserted only
1311 // at this point; if the client closes the
1312 // connection and reconnects, the suspension
1313 // time does not have any effect.
1314 //
1315 sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
1316 goto error_noreply;
1317 }
1318
1319 free(username);
1320 free(passwd);
1321 break;
1322 }
1323
1324 default:
1325 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE,
1326 "Authentication type not recognized.");
1327 if (rpcap_senderror(pars->sockctrl, pars->ssl,
1328 0, PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1)
1329 {
1330 // That failed; log a message and give up.
1331 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1332 return -1;
1333 }
1334 goto error_noreply;
1335 }
1336
1337 // The authentication succeeded; let the client know.
1338 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1339 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1340 goto error;
1341
1342 rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
1343 RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply));
1344
1345 authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx];
1346
1347 if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx,
1348 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1349 goto error;
1350
1351 //
1352 // Indicate to our peer what versions we support.
1353 //
1354 memset(authreply, 0, sizeof(struct rpcap_authreply));
1355 authreply->minvers = RPCAP_MIN_VERSION;
1356 authreply->maxvers = RPCAP_MAX_VERSION;
1357
1358 // Send the reply.
1359 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1360 {
1361 // That failed; log a messsage and give up.
1362 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1363 return -1;
1364 }
1365
1366 // Check if all the data has been read; if not, discard the data in excess
1367 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1368 {
1369 return -1;
1370 }
1371
1372 return 0;
1373
1374 error:
1375 if (rpcap_senderror(pars->sockctrl, pars->ssl, 0, PCAP_ERR_AUTH,
1376 errmsgbuf, errbuf) == -1)
1377 {
1378 // That failed; log a message and give up.
1379 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1380 return -1;
1381 }
1382
1383 error_noreply:
1384 // Check if all the data has been read; if not, discard the data in excess
1385 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1386 {
1387 return -1;
1388 }
1389
1390 return -2;
1391 }
1392
1393 static int
1394 daemon_AuthUserPwd(char *username, char *password, char *errbuf)
1395 {
1396 #ifdef _WIN32
1397 /*
1398 * Warning: the user which launches the process must have the
1399 * SE_TCB_NAME right.
1400 * This corresponds to have the "Act as part of the Operating System"
1401 * turned on (administrative tools, local security settings, local
1402 * policies, user right assignment)
1403 * However, it seems to me that if you run it as a service, this
1404 * right should be provided by default.
1405 *
1406 * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
1407 * which merely indicates that the user name or password is
1408 * incorrect, not whether it's the user name or the password
1409 * that's incorrect, so a client that's trying to brute-force
1410 * accounts doesn't know whether it's the user name or the
1411 * password that's incorrect, so it doesn't know whether to
1412 * stop trying to log in with a given user name and move on
1413 * to another user name.
1414 */
1415 HANDLE Token;
1416 if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
1417 {
1418 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
1419 GetLastError(), "LogonUser() failed");
1420 return -1;
1421 }
1422
1423 // This call should change the current thread to the selected user.
1424 // I didn't test it.
1425 if (ImpersonateLoggedOnUser(Token) == 0)
1426 {
1427 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
1428 GetLastError(), "ImpersonateLoggedOnUser() failed");
1429 CloseHandle(Token);
1430 return -1;
1431 }
1432
1433 CloseHandle(Token);
1434 return 0;
1435
1436 #else
1437 /*
1438 * See
1439 *
1440 * http://www.unixpapa.com/incnote/passwd.html
1441 *
1442 * We use the Solaris/Linux shadow password authentication if
1443 * we have getspnam(), otherwise we just do traditional
1444 * authentication, which, on some platforms, might work, even
1445 * with shadow passwords, if we're running as root. Traditional
1446 * authenticaion won't work if we're not running as root, as
1447 * I think these days all UN*Xes either won't return the password
1448 * at all with getpwnam() or will only do so if you're root.
1449 *
1450 * XXX - perhaps what we *should* be using is PAM, if we have
1451 * it. That might hide all the details of username/password
1452 * authentication, whether it's done with a visible-to-root-
1453 * only password database or some other authentication mechanism,
1454 * behind its API.
1455 */
1456 struct passwd *user;
1457 char *user_password;
1458 #ifdef HAVE_GETSPNAM
1459 struct spwd *usersp;
1460 #endif
1461
1462 // This call is needed to get the uid
1463 if ((user = getpwnam(username)) == NULL)
1464 {
1465 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1466 return -1;
1467 }
1468
1469 #ifdef HAVE_GETSPNAM
1470 // This call is needed to get the password; otherwise 'x' is returned
1471 if ((usersp = getspnam(username)) == NULL)
1472 {
1473 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1474 return -1;
1475 }
1476 user_password = usersp->sp_pwdp;
1477 #else
1478 /*
1479 * XXX - what about other platforms?
1480 * The unixpapa.com page claims this Just Works on *BSD if you're
1481 * running as root - it's from 2000, so it doesn't indicate whether
1482 * macOS (which didn't come out until 2001, under the name Mac OS
1483 * X) behaves like the *BSDs or not, and might also work on AIX.
1484 * HP-UX does something else.
1485 *
1486 * Again, hopefully PAM hides all that.
1487 */
1488 user_password = user->pw_passwd;
1489 #endif
1490
1491 if (strcmp(user_password, (char *) crypt(password, user_password)) != 0)
1492 {
1493 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1494 return -1;
1495 }
1496
1497 if (setuid(user->pw_uid))
1498 {
1499 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1500 errno, "setuid");
1501 return -1;
1502 }
1503
1504 /* if (setgid(user->pw_gid))
1505 {
1506 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1507 errno, "setgid");
1508 return -1;
1509 }
1510 */
1511 return 0;
1512
1513 #endif
1514
1515 }
1516
1517 static int
1518 daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
1519 {
1520 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1521 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1522 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1523 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1524 pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
1525 pcap_if_t *d; // temp pointer needed to scan the interface chain
1526 struct pcap_addr *address; // pcap structure that keeps a network address of an interface
1527 struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
1528 uint16 nif = 0; // counts the number of interface listed
1529
1530 // Discard the rest of the message; there shouldn't be any payload.
1531 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1532 {
1533 // Network error.
1534 return -1;
1535 }
1536
1537 // Retrieve the device list
1538 if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
1539 goto error;
1540
1541 if (alldevs == NULL)
1542 {
1543 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
1544 PCAP_ERR_NOREMOTEIF,
1545 "No interfaces found! Make sure libpcap/WinPcap is properly installed"
1546 " and you have the right to access to the remote device.",
1547 errbuf) == -1)
1548 {
1549 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1550 return -1;
1551 }
1552 return 0;
1553 }
1554
1555 // checks the number of interfaces and it computes the total length of the payload
1556 for (d = alldevs; d != NULL; d = d->next)
1557 {
1558 nif++;
1559
1560 if (d->description)
1561 plen+= strlen(d->description);
1562 if (d->name)
1563 plen+= strlen(d->name);
1564
1565 plen+= sizeof(struct rpcap_findalldevs_if);
1566
1567 for (address = d->addresses; address != NULL; address = address->next)
1568 {
1569 /*
1570 * Send only IPv4 and IPv6 addresses over the wire.
1571 */
1572 switch (address->addr->sa_family)
1573 {
1574 case AF_INET:
1575 #ifdef AF_INET6
1576 case AF_INET6:
1577 #endif
1578 plen+= (sizeof(struct rpcap_sockaddr) * 4);
1579 break;
1580
1581 default:
1582 break;
1583 }
1584 }
1585 }
1586
1587 // RPCAP findalldevs command
1588 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1589 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
1590 PCAP_ERRBUF_SIZE) == -1)
1591 goto error;
1592
1593 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
1594 RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
1595
1596 // send the interface list
1597 for (d = alldevs; d != NULL; d = d->next)
1598 {
1599 uint16 lname, ldescr;
1600
1601 findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
1602
1603 if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
1604 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1605 goto error;
1606
1607 memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
1608
1609 if (d->description) ldescr = (short) strlen(d->description);
1610 else ldescr = 0;
1611 if (d->name) lname = (short) strlen(d->name);
1612 else lname = 0;
1613
1614 findalldevs_if->desclen = htons(ldescr);
1615 findalldevs_if->namelen = htons(lname);
1616 findalldevs_if->flags = htonl(d->flags);
1617
1618 for (address = d->addresses; address != NULL; address = address->next)
1619 {
1620 /*
1621 * Send only IPv4 and IPv6 addresses over the wire.
1622 */
1623 switch (address->addr->sa_family)
1624 {
1625 case AF_INET:
1626 #ifdef AF_INET6
1627 case AF_INET6:
1628 #endif
1629 findalldevs_if->naddr++;
1630 break;
1631
1632 default:
1633 break;
1634 }
1635 }
1636 findalldevs_if->naddr = htons(findalldevs_if->naddr);
1637
1638 if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
1639 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1640 PCAP_ERRBUF_SIZE) == -1)
1641 goto error;
1642
1643 if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
1644 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1645 PCAP_ERRBUF_SIZE) == -1)
1646 goto error;
1647
1648 // send all addresses
1649 for (address = d->addresses; address != NULL; address = address->next)
1650 {
1651 struct rpcap_sockaddr *sockaddr;
1652
1653 /*
1654 * Send only IPv4 and IPv6 addresses over the wire.
1655 */
1656 switch (address->addr->sa_family)
1657 {
1658 case AF_INET:
1659 #ifdef AF_INET6
1660 case AF_INET6:
1661 #endif
1662 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1663 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1664 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1665 goto error;
1666 daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
1667
1668 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1669 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1670 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1671 goto error;
1672 daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
1673
1674 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1675 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1676 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1677 goto error;
1678 daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
1679
1680 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1681 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1682 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1683 goto error;
1684 daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
1685 break;
1686
1687 default:
1688 break;
1689 }
1690 }
1691 }
1692
1693 // We no longer need the device list. Free it.
1694 pcap_freealldevs(alldevs);
1695
1696 // Send a final command that says "now send it!"
1697 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1698 {
1699 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1700 return -1;
1701 }
1702
1703 return 0;
1704
1705 error:
1706 if (alldevs)
1707 pcap_freealldevs(alldevs);
1708
1709 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
1710 PCAP_ERR_FINDALLIF, errmsgbuf, errbuf) == -1)
1711 {
1712 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1713 return -1;
1714 }
1715 return 0;
1716 }
1717
1718 /*
1719 \param plen: the length of the current message (needed in order to be able
1720 to discard excess data in the message, if present)
1721 */
1722 static int
1723 daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
1724 char *source, size_t sourcelen)
1725 {
1726 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1727 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1728 pcap_t *fp; // pcap_t main variable
1729 int nread;
1730 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1731 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1732 struct rpcap_openreply *openreply; // open reply message
1733
1734 if (plen > sourcelen - 1)
1735 {
1736 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
1737 goto error;
1738 }
1739
1740 nread = sock_recv(pars->sockctrl, pars->ssl, source, plen,
1741 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
1742 if (nread == -1)
1743 {
1744 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1745 return -1;
1746 }
1747 source[nread] = '\0';
1748 plen -= nread;
1749
1750 // XXX - make sure it's *not* a URL; we don't support opening
1751 // remote devices here.
1752
1753 // Open the selected device
1754 // This is a fake open, since we do that only to get the needed parameters, then we close the device again
1755 if ((fp = pcap_open_live(source,
1756 1500 /* fake snaplen */,
1757 0 /* no promis */,
1758 1000 /* fake timeout */,
1759 errmsgbuf)) == NULL)
1760 goto error;
1761
1762 // Now, I can send a RPCAP open reply message
1763 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1764 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1765 goto error;
1766
1767 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
1768 RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
1769
1770 openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
1771
1772 if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
1773 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1774 goto error;
1775
1776 memset(openreply, 0, sizeof(struct rpcap_openreply));
1777 openreply->linktype = htonl(pcap_datalink(fp));
1778 /*
1779 * This is always 0 for live captures; we no longer support it
1780 * as something we read from capture files and supply to
1781 * clients, but we have to send it over the wire, as open
1782 * replies are expected to have 8 bytes of payload by
1783 * existing clients.
1784 */
1785 openreply->tzoff = 0;
1786
1787 // We're done with the pcap_t.
1788 pcap_close(fp);
1789
1790 // Send the reply.
1791 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1792 {
1793 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1794 return -1;
1795 }
1796 return 0;
1797
1798 error:
1799 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_OPEN,
1800 errmsgbuf, errbuf) == -1)
1801 {
1802 // That failed; log a message and give up.
1803 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1804 return -1;
1805 }
1806
1807 // Check if all the data has been read; if not, discard the data in excess
1808 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1809 {
1810 return -1;
1811 }
1812 return 0;
1813 }
1814
1815 /*
1816 \param plen: the length of the current message (needed in order to be able
1817 to discard excess data in the message, if present)
1818 */
1819 static int
1820 daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
1821 char *source, struct session **sessionp,
1822 struct rpcap_sampling *samp_param _U_, int uses_ssl)
1823 {
1824 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1825 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1826 char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
1827 char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
1828 struct session *session = NULL; // saves state of session
1829 int status;
1830 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1831 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1832
1833 // socket-related variables
1834 struct addrinfo hints; // temp, needed to open a socket connection
1835 struct addrinfo *addrinfo; // temp, needed to open a socket connection
1836 struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
1837 socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
1838 int ret; // return value from functions
1839
1840 // RPCAP-related variables
1841 struct rpcap_startcapreq startcapreq; // start capture request message
1842 struct rpcap_startcapreply *startcapreply; // start capture reply message
1843 int serveropen_dp; // keeps who is going to open the data connection
1844
1845 addrinfo = NULL;
1846
1847 status = rpcapd_recv(pars->sockctrl, pars->ssl, (char *) &startcapreq,
1848 sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
1849 if (status == -1)
1850 {
1851 goto fatal_error;
1852 }
1853 if (status == -2)
1854 {
1855 goto error;
1856 }
1857
1858 startcapreq.flags = ntohs(startcapreq.flags);
1859
1860 // Check that the client does not ask for UDP is the server has been asked
1861 // to enforce encryption, as SSL is not supported yet with UDP:
1862 if (uses_ssl && (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM))
1863 {
1864 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1865 "SSL not supported with UDP forward of remote packets");
1866 goto error;
1867 }
1868
1869 // Create a session structure
1870 session = malloc(sizeof(struct session));
1871 if (session == NULL)
1872 {
1873 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
1874 goto error;
1875 }
1876
1877 session->sockdata = INVALID_SOCKET;
1878 session->ctrl_ssl = session->data_ssl = NULL;
1879 // We don't have a thread yet.
1880 session->have_thread = 0;
1881 //
1882 // We *shouldn't* have to initialize the thread indicator
1883 // itself, because the compiler *should* realize that we
1884 // only use this if have_thread isn't 0, but we *do* have
1885 // to do it, because not all compilers *do* realize that.
1886 //
1887 // There is no "invalid thread handle" value for a UN*X
1888 // pthread_t, so we just zero it out.
1889 //
1890 #ifdef _WIN32
1891 session->thread = INVALID_HANDLE_VALUE;
1892 #else
1893 memset(&session->thread, 0, sizeof(session->thread));
1894 #endif
1895
1896 // Open the selected device
1897 if ((session->fp = pcap_open_live(source,
1898 ntohl(startcapreq.snaplen),
1899 (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
1900 ntohl(startcapreq.read_timeout),
1901 errmsgbuf)) == NULL)
1902 goto error;
1903
1904 #if 0
1905 // Apply sampling parameters
1906 fp->rmt_samp.method = samp_param->method;
1907 fp->rmt_samp.value = samp_param->value;
1908 #endif
1909
1910 /*
1911 We're in active mode if:
1912 - we're using TCP, and the user wants us to be in active mode
1913 - we're using UDP
1914 */
1915 serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
1916
1917 /*
1918 Gets the sockaddr structure referred to the other peer in the ctrl connection
1919
1920 We need that because:
1921 - if we're in passive mode, we need to know the address family we want to use
1922 (the same used for the ctrl socket)
1923 - if we're in active mode, we need to know the network address of the other host
1924 we want to connect to
1925 */
1926 saddrlen = sizeof(struct sockaddr_storage);
1927 if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1928 {
1929 sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE);
1930 goto error;
1931 }
1932
1933 memset(&hints, 0, sizeof(struct addrinfo));
1934 hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
1935 hints.ai_family = saddr.ss_family;
1936
1937 // Now we have to create a new socket to send packets
1938 if (serveropen_dp) // Data connection is opened by the server toward the client
1939 {
1940 pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
1941
1942 // Get the name of the other peer (needed to connect to that specific network address)
1943 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
1944 sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
1945 {
1946 sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
1947 goto error;
1948 }
1949
1950 if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1951 goto error;
1952
1953 if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1954 goto error;
1955 }
1956 else // Data connection is opened by the client toward the server
1957 {
1958 hints.ai_flags = AI_PASSIVE;
1959
1960 // Let's the server socket pick up a free network port for us
1961 if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1962 goto error;
1963
1964 if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1965 goto error;
1966
1967 // get the complete sockaddr structure used in the data connection
1968 saddrlen = sizeof(struct sockaddr_storage);
1969 if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1970 {
1971 sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE);
1972 goto error;
1973 }
1974
1975 // Get the local port the system picked up
1976 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1977 0, portdata, sizeof(portdata), NI_NUMERICSERV))
1978 {
1979 sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE);
1980 goto error;
1981 }
1982 }
1983
1984 // addrinfo is no longer used
1985 freeaddrinfo(addrinfo);
1986 addrinfo = NULL;
1987
1988 // Needed to send an error on the ctrl connection
1989 session->sockctrl = pars->sockctrl;
1990 session->ctrl_ssl = pars->ssl;
1991 session->protocol_version = ver;
1992
1993 // Now I can set the filter
1994 ret = daemon_unpackapplyfilter(pars->sockctrl, pars->ssl, session, &plen, errmsgbuf);
1995 if (ret == -1)
1996 {
1997 // Fatal error. A message has been logged; just give up.
1998 goto fatal_error;
1999 }
2000 if (ret == -2)
2001 {
2002 // Non-fatal error. Send an error message to the client.
2003 goto error;
2004 }
2005
2006 // Now, I can send a RPCAP start capture reply message
2007 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
2008 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2009 goto error;
2010
2011 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
2012 RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
2013
2014 startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
2015
2016 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
2017 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2018 goto error;
2019
2020 memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
2021 startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
2022
2023 if (!serveropen_dp)
2024 {
2025 unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
2026 startcapreply->portdata = htons(port);
2027 }
2028
2029 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
2030 {
2031 // That failed; log a message and give up.
2032 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2033 goto fatal_error;
2034 }
2035
2036 if (!serveropen_dp)
2037 {
2038 SOCKET socktemp; // We need another socket, since we're going to accept() a connection
2039
2040 // Connection creation
2041 saddrlen = sizeof(struct sockaddr_storage);
2042
2043 socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
2044
2045 if (socktemp == INVALID_SOCKET)
2046 {
2047 sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
2048 rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
2049 errbuf);
2050 goto error;
2051 }
2052
2053 // Now that I accepted the connection, the server socket is no longer needed
2054 sock_close(session->sockdata, NULL, 0);
2055 session->sockdata = socktemp;
2056 }
2057
2058 SSL *ssl = NULL;
2059 if (uses_ssl)
2060 {
2061 #ifdef HAVE_OPENSSL
2062 /* In both active or passive cases, wait for the client to initiate the
2063 * TLS handshake. Yes during that time the control socket will not be
2064 * served, but the same was true from the above call to accept(). */
2065 ssl = ssl_promotion(1, session->sockdata, errbuf, PCAP_ERRBUF_SIZE);
2066 if (! ssl)
2067 {
2068 rpcapd_log(LOGPRIO_ERROR, "TLS handshake failed: %s", errbuf);
2069 goto error;
2070 }
2071 #endif
2072 }
2073 session->data_ssl = ssl;
2074
2075 // Now we have to create a new thread to receive packets
2076 #ifdef _WIN32
2077 session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
2078 (void *) session, 0, NULL);
2079 if (session->thread == 0)
2080 {
2081 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
2082 goto error;
2083 }
2084 #else
2085 ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
2086 (void *) session);
2087 if (ret != 0)
2088 {
2089 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2090 ret, "Error creating the data thread");
2091 goto error;
2092 }
2093 #endif
2094 session->have_thread = 1;
2095
2096 // Check if all the data has been read; if not, discard the data in excess
2097 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2098 goto fatal_error;
2099
2100 *sessionp = session;
2101 return 0;
2102
2103 error:
2104 //
2105 // Not a fatal error, so send the client an error message and
2106 // keep serving client requests.
2107 //
2108 *sessionp = NULL;
2109
2110 if (addrinfo)
2111 freeaddrinfo(addrinfo);
2112
2113 if (session)
2114 {
2115 session_close(session);
2116 free(session);
2117 }
2118
2119 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
2120 PCAP_ERR_STARTCAPTURE, errmsgbuf, errbuf) == -1)
2121 {
2122 // That failed; log a message and give up.
2123 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2124 return -1;
2125 }
2126
2127 // Check if all the data has been read; if not, discard the data in excess
2128 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2129 {
2130 // Network error.
2131 return -1;
2132 }
2133
2134 return 0;
2135
2136 fatal_error:
2137 //
2138 // Fatal network error, so don't try to communicate with
2139 // the client, just give up.
2140 //
2141 *sessionp = NULL;
2142
2143 if (session)
2144 {
2145 session_close(session);
2146 free(session);
2147 }
2148
2149 return -1;
2150 }
2151
2152 static int
2153 daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
2154 struct session *session)
2155 {
2156 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2157 struct rpcap_header header;
2158
2159 session_close(session);
2160
2161 rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
2162
2163 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2164 {
2165 // That failed; log a message and give up.
2166 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2167 return -1;
2168 }
2169
2170 return 0;
2171 }
2172
2173 static int
2174 daemon_unpackapplyfilter(SOCKET sockctrl, SSL *ctrl_ssl, struct session *session, uint32 *plenp, char *errmsgbuf)
2175 {
2176 int status;
2177 struct rpcap_filter filter;
2178 struct rpcap_filterbpf_insn insn;
2179 struct bpf_insn *bf_insn;
2180 struct bpf_program bf_prog;
2181 unsigned int i;
2182
2183 status = rpcapd_recv(sockctrl, ctrl_ssl, (char *) &filter,
2184 sizeof(struct rpcap_filter), plenp, errmsgbuf);
2185 if (status == -1)
2186 {
2187 return -1;
2188 }
2189 if (status == -2)
2190 {
2191 return -2;
2192 }
2193
2194 bf_prog.bf_len = ntohl(filter.nitems);
2195
2196 if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
2197 {
2198 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
2199 return -2;
2200 }
2201
2202 bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
2203 if (bf_insn == NULL)
2204 {
2205 pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
2206 errno, "malloc() failed");
2207 return -2;
2208 }
2209
2210 bf_prog.bf_insns = bf_insn;
2211
2212 for (i = 0; i < bf_prog.bf_len; i++)
2213 {
2214 status = rpcapd_recv(sockctrl, ctrl_ssl, (char *) &insn,
2215 sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
2216 if (status == -1)
2217 {
2218 return -1;
2219 }
2220 if (status == -2)
2221 {
2222 return -2;
2223 }
2224
2225 bf_insn->code = ntohs(insn.code);
2226 bf_insn->jf = insn.jf;
2227 bf_insn->jt = insn.jt;
2228 bf_insn->k = ntohl(insn.k);
2229
2230 bf_insn++;
2231 }
2232
2233 //
2234 // XXX - pcap_setfilter() should do the validation for us.
2235 //
2236 if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
2237 {
2238 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
2239 return -2;
2240 }
2241
2242 if (pcap_setfilter(session->fp, &bf_prog))
2243 {
2244 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
2245 return -2;
2246 }
2247
2248 return 0;
2249 }
2250
2251 static int
2252 daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
2253 struct session *session, uint32 plen)
2254 {
2255 char errbuf[PCAP_ERRBUF_SIZE];
2256 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2257 int ret; // status of daemon_unpackapplyfilter()
2258 struct rpcap_header header; // keeps the answer to the updatefilter command
2259
2260 ret = daemon_unpackapplyfilter(pars->sockctrl, pars->ssl, session, &plen, errmsgbuf);
2261 if (ret == -1)
2262 {
2263 // Fatal error. A message has been logged; just give up.
2264 return -1;
2265 }
2266 if (ret == -2)
2267 {
2268 // Non-fatal error. Send an error reply to the client.
2269 goto error;
2270 }
2271
2272 // Check if all the data has been read; if not, discard the data in excess
2273 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2274 {
2275 // Network error.
2276 return -1;
2277 }
2278
2279 // A response is needed, otherwise the other host does not know that everything went well
2280 rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
2281
2282 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
2283 {
2284 // That failed; log a messsage and give up.
2285 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2286 return -1;
2287 }
2288
2289 return 0;
2290
2291 error:
2292 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2293 {
2294 return -1;
2295 }
2296 rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_UPDATEFILTER,
2297 errmsgbuf, NULL);
2298
2299 return 0;
2300 }
2301
2302 /*!
2303 \brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
2304 */
2305 static int
2306 daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
2307 struct rpcap_sampling *samp_param)
2308 {
2309 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2310 char errmsgbuf[PCAP_ERRBUF_SIZE];
2311 struct rpcap_header header;
2312 struct rpcap_sampling rpcap_samp;
2313 int status;
2314
2315 status = rpcapd_recv(pars->sockctrl, pars->ssl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
2316 if (status == -1)
2317 {
2318 return -1;
2319 }
2320 if (status == -2)
2321 {
2322 goto error;
2323 }
2324
2325 // Save these settings in the pcap_t
2326 samp_param->method = rpcap_samp.method;
2327 samp_param->value = ntohl(rpcap_samp.value);
2328
2329 // A response is needed, otherwise the other host does not know that everything went well
2330 rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
2331
2332 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2333 {
2334 // That failed; log a messsage and give up.
2335 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2336 return -1;
2337 }
2338
2339 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2340 {
2341 return -1;
2342 }
2343
2344 return 0;
2345
2346 error:
2347 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_SETSAMPLING,
2348 errmsgbuf, errbuf) == -1)
2349 {
2350 // That failed; log a message and give up.
2351 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2352 return -1;
2353 }
2354
2355 // Check if all the data has been read; if not, discard the data in excess
2356 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2357 {
2358 return -1;
2359 }
2360
2361 return 0;
2362 }
2363
2364 static int
2365 daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
2366 struct session *session, uint32 plen, struct pcap_stat *stats,
2367 unsigned int svrcapt)
2368 {
2369 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2370 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2371 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
2372 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
2373 struct rpcap_stats *netstats; // statistics sent on the network
2374
2375 // Checks that the header does not contain other data; if so, discard it
2376 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2377 {
2378 // Network error.
2379 return -1;
2380 }
2381
2382 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2383 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2384 goto error;
2385
2386 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
2387 RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
2388
2389 netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
2390
2391 if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
2392 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2393 goto error;
2394
2395 if (session && session->fp)
2396 {
2397 if (pcap_stats(session->fp, stats) == -1)
2398 {
2399 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
2400 goto error;
2401 }
2402
2403 netstats->ifdrop = htonl(stats->ps_ifdrop);
2404 netstats->ifrecv = htonl(stats->ps_recv);
2405 netstats->krnldrop = htonl(stats->ps_drop);
2406 netstats->svrcapt = htonl(session->TotCapt);
2407 }
2408 else
2409 {
2410 // We have to keep compatibility with old applications,
2411 // which ask for statistics also when the capture has
2412 // already stopped.
2413 netstats->ifdrop = htonl(stats->ps_ifdrop);
2414 netstats->ifrecv = htonl(stats->ps_recv);
2415 netstats->krnldrop = htonl(stats->ps_drop);
2416 netstats->svrcapt = htonl(svrcapt);
2417 }
2418
2419 // Send the packet
2420 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
2421 {
2422 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2423 return -1;
2424 }
2425
2426 return 0;
2427
2428 error:
2429 rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_GETSTATS,
2430 errmsgbuf, NULL);
2431 return 0;
2432 }
2433
2434 #ifdef _WIN32
2435 static unsigned __stdcall
2436 #else
2437 static void *
2438 #endif
2439 daemon_thrdatamain(void *ptr)
2440 {
2441 char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
2442 struct session *session; // pointer to the struct session for this session
2443 int retval; // general variable used to keep the return value of other functions
2444 struct rpcap_pkthdr *net_pkt_header;// header of the packet
2445 struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
2446 u_char *pkt_data; // pointer to the buffer that contains the current packet
2447 size_t sendbufsize; // size for the send buffer
2448 char *sendbuf; // temporary buffer in which data to be sent is buffered
2449 int sendbufidx; // index which keeps the number of bytes currently buffered
2450 int status;
2451 #ifndef _WIN32
2452 sigset_t sigusr1; // signal set with just SIGUSR1
2453 #endif
2454
2455 session = (struct session *) ptr;
2456
2457 session->TotCapt = 0; // counter which is incremented each time a packet is received
2458
2459 // Initialize errbuf
2460 memset(errbuf, 0, sizeof(errbuf));
2461
2462 //
2463 // We need a buffer large enough to hold a buffer large enough
2464 // for a maximum-size packet for this pcap_t.
2465 //
2466 if (pcap_snapshot(session->fp) < 0)
2467 {
2468 //
2469 // The snapshot length is negative.
2470 // This "should not happen".
2471 //
2472 rpcapd_log(LOGPRIO_ERROR,
2473 "Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
2474 pcap_snapshot(session->fp));
2475 sendbuf = NULL; // we can't allocate a buffer, so nothing to free
2476 goto error;
2477 }
2478 //
2479 // size_t is unsigned, and the result of pcap_snapshot() is signed;
2480 // on no platform that we support is int larger than size_t.
2481 // This means that, unless the extra information we prepend to
2482 // a maximum-sized packet is impossibly large, the sum of the
2483 // snapshot length and the size of that extra information will
2484 // fit in a size_t.
2485 //
2486 // So we don't need to make sure that sendbufsize will overflow.
2487 //
2488 // However, we *do* need to make sure its value fits in an int,
2489 // because sock_send() can't send more than INT_MAX bytes (it could
2490 // do so on 64-bit UN*Xes, but can't do so on Windows, not even
2491 // 64-bit Windows, as the send() buffer size argument is an int
2492 // in Winsock).
2493 //
2494 sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
2495 if (sendbufsize > INT_MAX)
2496 {
2497 rpcapd_log(LOGPRIO_ERROR,
2498 "Buffer size for this child thread would be larger than %d",
2499 INT_MAX);
2500 sendbuf = NULL; // we haven't allocated a buffer, so nothing to free
2501 goto error;
2502 }
2503 sendbuf = (char *) malloc (sendbufsize);
2504 if (sendbuf == NULL)
2505 {
2506 rpcapd_log(LOGPRIO_ERROR,
2507 "Unable to allocate the buffer for this child thread");
2508 goto error;
2509 }
2510
2511 #ifndef _WIN32
2512 //
2513 // Set the signal set to include just SIGUSR1, and block that
2514 // signal; we only want it unblocked when we're reading
2515 // packets - we dn't want any other system calls, such as
2516 // ones being used to send to the client or to log messages,
2517 // to be interrupted.
2518 //
2519 sigemptyset(&sigusr1);
2520 sigaddset(&sigusr1, SIGUSR1);
2521 pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
2522 #endif
2523
2524 // Retrieve the packets
2525 for (;;)
2526 {
2527 #ifndef _WIN32
2528 //
2529 // Unblock SIGUSR1 while we might be waiting for packets.
2530 //
2531 pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
2532 #endif
2533 retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
2534 #ifndef _WIN32
2535 //
2536 // Now block it again.
2537 //
2538 pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
2539 #endif
2540 if (retval < 0)
2541 break; // error
2542 if (retval == 0) // Read timeout elapsed
2543 continue;
2544
2545 sendbufidx = 0;
2546
2547 // Bufferize the general header
2548 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2549 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2550 PCAP_ERRBUF_SIZE) == -1)
2551 {
2552 rpcapd_log(LOGPRIO_ERROR,
2553 "sock_bufferize() error sending packet message: %s",
2554 errbuf);
2555 goto error;
2556 }
2557
2558 rpcap_createhdr((struct rpcap_header *) sendbuf,
2559 session->protocol_version, RPCAP_MSG_PACKET, 0,
2560 (uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
2561
2562 net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
2563
2564 // Bufferize the pkt header
2565 if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
2566 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2567 PCAP_ERRBUF_SIZE) == -1)
2568 {
2569 rpcapd_log(LOGPRIO_ERROR,
2570 "sock_bufferize() error sending packet message: %s",
2571 errbuf);
2572 goto error;
2573 }
2574
2575 net_pkt_header->caplen = htonl(pkt_header->caplen);
2576 net_pkt_header->len = htonl(pkt_header->len);
2577 net_pkt_header->npkt = htonl(++(session->TotCapt));
2578 //
2579 // This protocol needs to be updated with a new version
2580 // before 2038-01-19 03:14:07 UTC.
2581 //
2582 net_pkt_header->timestamp_sec = htonl((uint32)pkt_header->ts.tv_sec);
2583 net_pkt_header->timestamp_usec = htonl((uint32)pkt_header->ts.tv_usec);
2584
2585 // Bufferize the pkt data
2586 if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
2587 sendbuf, &sendbufidx, (int)sendbufsize, SOCKBUF_BUFFERIZE,
2588 errbuf, PCAP_ERRBUF_SIZE) == -1)
2589 {
2590 rpcapd_log(LOGPRIO_ERROR,
2591 "sock_bufferize() error sending packet message: %s",
2592 errbuf);
2593 goto error;
2594 }
2595
2596 // Send the packet
2597 // If the client dropped the connection, don't report an
2598 // error, just quit.
2599 status = sock_send(session->sockdata, session->data_ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
2600 if (status < 0)
2601 {
2602 if (status == -1)
2603 {
2604 //
2605 // Error other than "client closed the
2606 // connection out from under us"; report
2607 // it.
2608 //
2609 rpcapd_log(LOGPRIO_ERROR,
2610 "Send of packet to client failed: %s",
2611 errbuf);
2612 }
2613
2614 //
2615 // Give up in either case.
2616 //
2617 goto error;
2618 }
2619 }
2620
2621 if (retval < 0 && retval != PCAP_ERROR_BREAK)
2622 {
2623 //
2624 // Failed with an error other than "we were told to break
2625 // out of the loop".
2626 //
2627 // The latter just means that the client told us to stop
2628 // capturing, so there's no error to report.
2629 //
2630 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
2631 rpcap_senderror(session->sockctrl, session->ctrl_ssl, session->protocol_version,
2632 PCAP_ERR_READEX, errbuf, NULL);
2633 }
2634
2635 error:
2636 //
2637 // The main thread will clean up the session structure.
2638 //
2639 free(sendbuf);
2640
2641 return 0;
2642 }
2643
2644 #ifndef _WIN32
2645 //
2646 // Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
2647 // interrupt the data thread if it's blocked in a system call waiting
2648 // for packets to arrive.
2649 //
2650 static void noop_handler(int sign _U_)
2651 {
2652 }
2653 #endif
2654
2655 /*!
2656 \brief It serializes a network address.
2657
2658 It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
2659 that can be used to be sent on the network. Basically, it applies all the hton()
2660 conversion required to the input variable.
2661
2662 \param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
2663 serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
2664
2665 \param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
2666 the serialized data. This variable has to be allocated by the user.
2667
2668 \warning This function supports only AF_INET and AF_INET6 address families.
2669 */
2670 static void
2671 daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
2672 {
2673 memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
2674
2675 // There can be the case in which the sockaddrin is not available
2676 if (sockaddrin == NULL) return;
2677
2678 // Warning: we support only AF_INET and AF_INET6
2679 switch (sockaddrin->ss_family)
2680 {
2681 case AF_INET:
2682 {
2683 struct sockaddr_in *sockaddrin_ipv4;
2684 struct rpcap_sockaddr_in *sockaddrout_ipv4;
2685
2686 sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
2687 sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
2688 sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
2689 sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
2690 memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
2691 memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
2692 break;
2693 }
2694
2695 #ifdef AF_INET6
2696 case AF_INET6:
2697 {
2698 struct sockaddr_in6 *sockaddrin_ipv6;
2699 struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
2700
2701 sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
2702 sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
2703 sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
2704 sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
2705 sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
2706 memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
2707 sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
2708 break;
2709 }
2710 #endif
2711 }
2712 }
2713
2714
2715 /*!
2716 \brief Suspends a thread for secs seconds.
2717 */
2718 void sleep_secs(int secs)
2719 {
2720 #ifdef _WIN32
2721 Sleep(secs*1000);
2722 #else
2723 unsigned secs_remaining;
2724
2725 if (secs <= 0)
2726 return;
2727 secs_remaining = secs;
2728 while (secs_remaining != 0)
2729 secs_remaining = sleep(secs_remaining);
2730 #endif
2731 }
2732
2733 /*
2734 * Read the header of a message.
2735 */
2736 static int
2737 rpcapd_recv_msg_header(SOCKET sock, SSL *ssl, struct rpcap_header *headerp)
2738 {
2739 int nread;
2740 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2741
2742 nread = sock_recv(sock, ssl, (char *) headerp, sizeof(struct rpcap_header),
2743 SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2744 if (nread == -1)
2745 {
2746 // Network error.
2747 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2748 return -1;
2749 }
2750 if (nread == 0)
2751 {
2752 // Immediate EOF; that's treated like a close message.
2753 return -2;
2754 }
2755 headerp->plen = ntohl(headerp->plen);
2756 return 0;
2757 }
2758
2759 /*
2760 * Read data from a message.
2761 * If we're trying to read more data that remains, puts an error
2762 * message into errmsgbuf and returns -2. Otherwise, tries to read
2763 * the data and, if that succeeds, subtracts the amount read from
2764 * the number of bytes of data that remains.
2765 * Returns 0 on success, logs a message and returns -1 on a network
2766 * error.
2767 */
2768 static int
2769 rpcapd_recv(SOCKET sock, SSL *ssl, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
2770 {
2771 int nread;
2772 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2773
2774 if (toread > *plen)
2775 {
2776 // Tell the client and continue.
2777 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
2778 return -2;
2779 }
2780 nread = sock_recv(sock, ssl, buffer, toread,
2781 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2782 if (nread == -1)
2783 {
2784 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2785 return -1;
2786 }
2787 *plen -= nread;
2788 return 0;
2789 }
2790
2791 /*
2792 * Discard data from a connection.
2793 * Mostly used to discard wrong-sized messages.
2794 * Returns 0 on success, logs a message and returns -1 on a network
2795 * error.
2796 */
2797 static int
2798 rpcapd_discard(SOCKET sock, SSL *ssl, uint32 len)
2799 {
2800 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
2801
2802 if (len != 0)
2803 {
2804 if (sock_discard(sock, ssl, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
2805 {
2806 // Network error.
2807 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2808 return -1;
2809 }
2810 }
2811 return 0;
2812 }
2813
2814 //
2815 // Shut down any packet-capture thread associated with the session,
2816 // close the SSL handle for the data socket if we have one, close
2817 // the data socket if we have one, and close the underlying packet
2818 // capture handle if we have one.
2819 //
2820 // We do not, of course, touch the controlling socket that's also
2821 // copied into the session, as the service loop might still use it.
2822 //
2823 static void session_close(struct session *session)
2824 {
2825 if (session->have_thread)
2826 {
2827 //
2828 // Tell the data connection thread main capture loop to
2829 // break out of that loop.
2830 //
2831 // This may be sufficient to wake up a blocked thread,
2832 // but it's not guaranteed to be sufficient.
2833 //
2834 pcap_breakloop(session->fp);
2835
2836 #ifdef _WIN32
2837 //
2838 // Set the event on which a read would block, so that,
2839 // if it's currently blocked waiting for packets to
2840 // arrive, it'll wake up, so it can see the "break
2841 // out of the loop" indication. (pcap_breakloop()
2842 // might do this, but older versions don't. Setting
2843 // it twice should, at worst, cause an extra wakeup,
2844 // which shouldn't be a problem.)
2845 //
2846 // XXX - what about modules other than NPF?
2847 //
2848 SetEvent(pcap_getevent(session->fp));
2849
2850 //
2851 // Wait for the thread to exit, so we don't close
2852 // sockets out from under it.
2853 //
2854 // XXX - have a timeout, so we don't wait forever?
2855 //
2856 WaitForSingleObject(session->thread, INFINITE);
2857
2858 //
2859 // Release the thread handle, as we're done with
2860 // it.
2861 //
2862 CloseHandle(session->thread);
2863 session->have_thread = 0;
2864 session->thread = INVALID_HANDLE_VALUE;
2865 #else
2866 //
2867 // Send a SIGUSR1 signal to the thread, so that, if
2868 // it's currently blocked waiting for packets to arrive,
2869 // it'll wake up (we've turned off SA_RESTART for
2870 // SIGUSR1, so that the system call in which it's blocked
2871 // should return EINTR rather than restarting).
2872 //
2873 pthread_kill(session->thread, SIGUSR1);
2874
2875 //
2876 // Wait for the thread to exit, so we don't close
2877 // sockets out from under it.
2878 //
2879 // XXX - have a timeout, so we don't wait forever?
2880 //
2881 pthread_join(session->thread, NULL);
2882 session->have_thread = 0;
2883 memset(&session->thread, 0, sizeof(session->thread));
2884 #endif
2885 }
2886
2887 #ifdef HAVE_OPENSSL
2888 if (session->data_ssl)
2889 {
2890 // Finish using the SSL handle for the socket.
2891 // This must be done *before* the socket is closed.
2892 ssl_finish(session->data_ssl);
2893 session->data_ssl = NULL;
2894 }
2895 #endif
2896
2897 if (session->sockdata != INVALID_SOCKET)
2898 {
2899 sock_close(session->sockdata, NULL, 0);
2900 session->sockdata = INVALID_SOCKET;
2901 }
2902
2903 if (session->fp)
2904 {
2905 pcap_close(session->fp);
2906 session->fp = NULL;
2907 }
2908 }