]> The Tcpdump Group git mirrors - libpcap/blob - rpcapd/daemon.c
Merge pull request #749 from nmap/manpage-formatting
[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_win32_err_to_str(GetLastError(), errbuf);
1419 return -1;
1420 }
1421
1422 // This call should change the current thread to the selected user.
1423 // I didn't test it.
1424 if (ImpersonateLoggedOnUser(Token) == 0)
1425 {
1426 pcap_win32_err_to_str(GetLastError(), errbuf);
1427 CloseHandle(Token);
1428 return -1;
1429 }
1430
1431 CloseHandle(Token);
1432 return 0;
1433
1434 #else
1435 /*
1436 * See
1437 *
1438 * http://www.unixpapa.com/incnote/passwd.html
1439 *
1440 * We use the Solaris/Linux shadow password authentication if
1441 * we have getspnam(), otherwise we just do traditional
1442 * authentication, which, on some platforms, might work, even
1443 * with shadow passwords, if we're running as root. Traditional
1444 * authenticaion won't work if we're not running as root, as
1445 * I think these days all UN*Xes either won't return the password
1446 * at all with getpwnam() or will only do so if you're root.
1447 *
1448 * XXX - perhaps what we *should* be using is PAM, if we have
1449 * it. That might hide all the details of username/password
1450 * authentication, whether it's done with a visible-to-root-
1451 * only password database or some other authentication mechanism,
1452 * behind its API.
1453 */
1454 struct passwd *user;
1455 char *user_password;
1456 #ifdef HAVE_GETSPNAM
1457 struct spwd *usersp;
1458 #endif
1459
1460 // This call is needed to get the uid
1461 if ((user = getpwnam(username)) == NULL)
1462 {
1463 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1464 return -1;
1465 }
1466
1467 #ifdef HAVE_GETSPNAM
1468 // This call is needed to get the password; otherwise 'x' is returned
1469 if ((usersp = getspnam(username)) == NULL)
1470 {
1471 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1472 return -1;
1473 }
1474 user_password = usersp->sp_pwdp;
1475 #else
1476 /*
1477 * XXX - what about other platforms?
1478 * The unixpapa.com page claims this Just Works on *BSD if you're
1479 * running as root - it's from 2000, so it doesn't indicate whether
1480 * macOS (which didn't come out until 2001, under the name Mac OS
1481 * X) behaves like the *BSDs or not, and might also work on AIX.
1482 * HP-UX does something else.
1483 *
1484 * Again, hopefully PAM hides all that.
1485 */
1486 user_password = user->pw_passwd;
1487 #endif
1488
1489 if (strcmp(user_password, (char *) crypt(password, user_password)) != 0)
1490 {
1491 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
1492 return -1;
1493 }
1494
1495 if (setuid(user->pw_uid))
1496 {
1497 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1498 errno, "setuid");
1499 return -1;
1500 }
1501
1502 /* if (setgid(user->pw_gid))
1503 {
1504 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1505 errno, "setgid");
1506 return -1;
1507 }
1508 */
1509 return 0;
1510
1511 #endif
1512
1513 }
1514
1515 static int
1516 daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
1517 {
1518 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1519 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1520 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1521 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1522 pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
1523 pcap_if_t *d; // temp pointer needed to scan the interface chain
1524 struct pcap_addr *address; // pcap structure that keeps a network address of an interface
1525 struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
1526 uint16 nif = 0; // counts the number of interface listed
1527
1528 // Discard the rest of the message; there shouldn't be any payload.
1529 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1530 {
1531 // Network error.
1532 return -1;
1533 }
1534
1535 // Retrieve the device list
1536 if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
1537 goto error;
1538
1539 if (alldevs == NULL)
1540 {
1541 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
1542 PCAP_ERR_NOREMOTEIF,
1543 "No interfaces found! Make sure libpcap/WinPcap is properly installed"
1544 " and you have the right to access to the remote device.",
1545 errbuf) == -1)
1546 {
1547 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1548 return -1;
1549 }
1550 return 0;
1551 }
1552
1553 // checks the number of interfaces and it computes the total length of the payload
1554 for (d = alldevs; d != NULL; d = d->next)
1555 {
1556 nif++;
1557
1558 if (d->description)
1559 plen+= strlen(d->description);
1560 if (d->name)
1561 plen+= strlen(d->name);
1562
1563 plen+= sizeof(struct rpcap_findalldevs_if);
1564
1565 for (address = d->addresses; address != NULL; address = address->next)
1566 {
1567 /*
1568 * Send only IPv4 and IPv6 addresses over the wire.
1569 */
1570 switch (address->addr->sa_family)
1571 {
1572 case AF_INET:
1573 #ifdef AF_INET6
1574 case AF_INET6:
1575 #endif
1576 plen+= (sizeof(struct rpcap_sockaddr) * 4);
1577 break;
1578
1579 default:
1580 break;
1581 }
1582 }
1583 }
1584
1585 // RPCAP findalldevs command
1586 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1587 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
1588 PCAP_ERRBUF_SIZE) == -1)
1589 goto error;
1590
1591 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
1592 RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
1593
1594 // send the interface list
1595 for (d = alldevs; d != NULL; d = d->next)
1596 {
1597 uint16 lname, ldescr;
1598
1599 findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
1600
1601 if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
1602 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1603 goto error;
1604
1605 memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
1606
1607 if (d->description) ldescr = (short) strlen(d->description);
1608 else ldescr = 0;
1609 if (d->name) lname = (short) strlen(d->name);
1610 else lname = 0;
1611
1612 findalldevs_if->desclen = htons(ldescr);
1613 findalldevs_if->namelen = htons(lname);
1614 findalldevs_if->flags = htonl(d->flags);
1615
1616 for (address = d->addresses; address != NULL; address = address->next)
1617 {
1618 /*
1619 * Send only IPv4 and IPv6 addresses over the wire.
1620 */
1621 switch (address->addr->sa_family)
1622 {
1623 case AF_INET:
1624 #ifdef AF_INET6
1625 case AF_INET6:
1626 #endif
1627 findalldevs_if->naddr++;
1628 break;
1629
1630 default:
1631 break;
1632 }
1633 }
1634 findalldevs_if->naddr = htons(findalldevs_if->naddr);
1635
1636 if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
1637 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1638 PCAP_ERRBUF_SIZE) == -1)
1639 goto error;
1640
1641 if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
1642 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1643 PCAP_ERRBUF_SIZE) == -1)
1644 goto error;
1645
1646 // send all addresses
1647 for (address = d->addresses; address != NULL; address = address->next)
1648 {
1649 struct rpcap_sockaddr *sockaddr;
1650
1651 /*
1652 * Send only IPv4 and IPv6 addresses over the wire.
1653 */
1654 switch (address->addr->sa_family)
1655 {
1656 case AF_INET:
1657 #ifdef AF_INET6
1658 case AF_INET6:
1659 #endif
1660 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1661 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1662 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1663 goto error;
1664 daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
1665
1666 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1667 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1668 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1669 goto error;
1670 daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
1671
1672 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1673 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1674 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1675 goto error;
1676 daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
1677
1678 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1679 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1680 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1681 goto error;
1682 daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
1683 break;
1684
1685 default:
1686 break;
1687 }
1688 }
1689 }
1690
1691 // We no longer need the device list. Free it.
1692 pcap_freealldevs(alldevs);
1693
1694 // Send a final command that says "now send it!"
1695 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1696 {
1697 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1698 return -1;
1699 }
1700
1701 return 0;
1702
1703 error:
1704 if (alldevs)
1705 pcap_freealldevs(alldevs);
1706
1707 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
1708 PCAP_ERR_FINDALLIF, errmsgbuf, errbuf) == -1)
1709 {
1710 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1711 return -1;
1712 }
1713 return 0;
1714 }
1715
1716 /*
1717 \param plen: the length of the current message (needed in order to be able
1718 to discard excess data in the message, if present)
1719 */
1720 static int
1721 daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
1722 char *source, size_t sourcelen)
1723 {
1724 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1725 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1726 pcap_t *fp; // pcap_t main variable
1727 int nread;
1728 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1729 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1730 struct rpcap_openreply *openreply; // open reply message
1731
1732 if (plen > sourcelen - 1)
1733 {
1734 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
1735 goto error;
1736 }
1737
1738 nread = sock_recv(pars->sockctrl, pars->ssl, source, plen,
1739 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
1740 if (nread == -1)
1741 {
1742 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1743 return -1;
1744 }
1745 source[nread] = '\0';
1746 plen -= nread;
1747
1748 // XXX - make sure it's *not* a URL; we don't support opening
1749 // remote devices here.
1750
1751 // Open the selected device
1752 // This is a fake open, since we do that only to get the needed parameters, then we close the device again
1753 if ((fp = pcap_open_live(source,
1754 1500 /* fake snaplen */,
1755 0 /* no promis */,
1756 1000 /* fake timeout */,
1757 errmsgbuf)) == NULL)
1758 goto error;
1759
1760 // Now, I can send a RPCAP open reply message
1761 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1762 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1763 goto error;
1764
1765 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
1766 RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
1767
1768 openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
1769
1770 if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
1771 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1772 goto error;
1773
1774 memset(openreply, 0, sizeof(struct rpcap_openreply));
1775 openreply->linktype = htonl(pcap_datalink(fp));
1776 /*
1777 * This is always 0 for live captures; we no longer support it
1778 * as something we read from capture files and supply to
1779 * clients, but we have to send it over the wire, as open
1780 * replies are expected to have 8 bytes of payload by
1781 * existing clients.
1782 */
1783 openreply->tzoff = 0;
1784
1785 // We're done with the pcap_t.
1786 pcap_close(fp);
1787
1788 // Send the reply.
1789 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1790 {
1791 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1792 return -1;
1793 }
1794 return 0;
1795
1796 error:
1797 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_OPEN,
1798 errmsgbuf, errbuf) == -1)
1799 {
1800 // That failed; log a message and give up.
1801 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1802 return -1;
1803 }
1804
1805 // Check if all the data has been read; if not, discard the data in excess
1806 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
1807 {
1808 return -1;
1809 }
1810 return 0;
1811 }
1812
1813 /*
1814 \param plen: the length of the current message (needed in order to be able
1815 to discard excess data in the message, if present)
1816 */
1817 static int
1818 daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
1819 char *source, struct session **sessionp,
1820 struct rpcap_sampling *samp_param _U_, int uses_ssl)
1821 {
1822 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1823 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1824 char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
1825 char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
1826 struct session *session = NULL; // saves state of session
1827 int status;
1828 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1829 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1830
1831 // socket-related variables
1832 struct addrinfo hints; // temp, needed to open a socket connection
1833 struct addrinfo *addrinfo; // temp, needed to open a socket connection
1834 struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
1835 socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
1836 int ret; // return value from functions
1837
1838 // RPCAP-related variables
1839 struct rpcap_startcapreq startcapreq; // start capture request message
1840 struct rpcap_startcapreply *startcapreply; // start capture reply message
1841 int serveropen_dp; // keeps who is going to open the data connection
1842
1843 addrinfo = NULL;
1844
1845 status = rpcapd_recv(pars->sockctrl, pars->ssl, (char *) &startcapreq,
1846 sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
1847 if (status == -1)
1848 {
1849 goto fatal_error;
1850 }
1851 if (status == -2)
1852 {
1853 goto error;
1854 }
1855
1856 startcapreq.flags = ntohs(startcapreq.flags);
1857
1858 // Check that the client does not ask for UDP is the server has been asked
1859 // to enforce encryption, as SSL is not supported yet with UDP:
1860 if (uses_ssl && (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM))
1861 {
1862 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1863 "SSL not supported with UDP forward of remote packets");
1864 goto error;
1865 }
1866
1867 // Create a session structure
1868 session = malloc(sizeof(struct session));
1869 if (session == NULL)
1870 {
1871 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
1872 goto error;
1873 }
1874
1875 session->sockdata = INVALID_SOCKET;
1876 session->ctrl_ssl = session->data_ssl = NULL;
1877 // We don't have a thread yet.
1878 session->have_thread = 0;
1879 //
1880 // We *shouldn't* have to initialize the thread indicator
1881 // itself, because the compiler *should* realize that we
1882 // only use this if have_thread isn't 0, but we *do* have
1883 // to do it, because not all compilers *do* realize that.
1884 //
1885 // There is no "invalid thread handle" value for a UN*X
1886 // pthread_t, so we just zero it out.
1887 //
1888 #ifdef _WIN32
1889 session->thread = INVALID_HANDLE_VALUE;
1890 #else
1891 memset(&session->thread, 0, sizeof(session->thread));
1892 #endif
1893
1894 // Open the selected device
1895 if ((session->fp = pcap_open_live(source,
1896 ntohl(startcapreq.snaplen),
1897 (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
1898 ntohl(startcapreq.read_timeout),
1899 errmsgbuf)) == NULL)
1900 goto error;
1901
1902 #if 0
1903 // Apply sampling parameters
1904 fp->rmt_samp.method = samp_param->method;
1905 fp->rmt_samp.value = samp_param->value;
1906 #endif
1907
1908 /*
1909 We're in active mode if:
1910 - we're using TCP, and the user wants us to be in active mode
1911 - we're using UDP
1912 */
1913 serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
1914
1915 /*
1916 Gets the sockaddr structure referred to the other peer in the ctrl connection
1917
1918 We need that because:
1919 - if we're in passive mode, we need to know the address family we want to use
1920 (the same used for the ctrl socket)
1921 - if we're in active mode, we need to know the network address of the other host
1922 we want to connect to
1923 */
1924 saddrlen = sizeof(struct sockaddr_storage);
1925 if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1926 {
1927 sock_geterror("getpeername(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1928 goto error;
1929 }
1930
1931 memset(&hints, 0, sizeof(struct addrinfo));
1932 hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
1933 hints.ai_family = saddr.ss_family;
1934
1935 // Now we have to create a new socket to send packets
1936 if (serveropen_dp) // Data connection is opened by the server toward the client
1937 {
1938 pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
1939
1940 // Get the name of the other peer (needed to connect to that specific network address)
1941 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
1942 sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
1943 {
1944 sock_geterror("getnameinfo(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1945 goto error;
1946 }
1947
1948 if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1949 goto error;
1950
1951 if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1952 goto error;
1953 }
1954 else // Data connection is opened by the client toward the server
1955 {
1956 hints.ai_flags = AI_PASSIVE;
1957
1958 // Let's the server socket pick up a free network port for us
1959 if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1960 goto error;
1961
1962 if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1963 goto error;
1964
1965 // get the complete sockaddr structure used in the data connection
1966 saddrlen = sizeof(struct sockaddr_storage);
1967 if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1968 {
1969 sock_geterror("getsockname(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1970 goto error;
1971 }
1972
1973 // Get the local port the system picked up
1974 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1975 0, portdata, sizeof(portdata), NI_NUMERICSERV))
1976 {
1977 sock_geterror("getnameinfo(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1978 goto error;
1979 }
1980 }
1981
1982 // addrinfo is no longer used
1983 freeaddrinfo(addrinfo);
1984 addrinfo = NULL;
1985
1986 // Needed to send an error on the ctrl connection
1987 session->sockctrl = pars->sockctrl;
1988 session->ctrl_ssl = pars->ssl;
1989 session->protocol_version = ver;
1990
1991 // Now I can set the filter
1992 ret = daemon_unpackapplyfilter(pars->sockctrl, pars->ssl, session, &plen, errmsgbuf);
1993 if (ret == -1)
1994 {
1995 // Fatal error. A message has been logged; just give up.
1996 goto fatal_error;
1997 }
1998 if (ret == -2)
1999 {
2000 // Non-fatal error. Send an error message to the client.
2001 goto error;
2002 }
2003
2004 // Now, I can send a RPCAP start capture reply message
2005 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
2006 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2007 goto error;
2008
2009 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
2010 RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
2011
2012 startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
2013
2014 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
2015 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2016 goto error;
2017
2018 memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
2019 startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
2020
2021 if (!serveropen_dp)
2022 {
2023 unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
2024 startcapreply->portdata = htons(port);
2025 }
2026
2027 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
2028 {
2029 // That failed; log a message and give up.
2030 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2031 goto fatal_error;
2032 }
2033
2034 if (!serveropen_dp)
2035 {
2036 SOCKET socktemp; // We need another socket, since we're going to accept() a connection
2037
2038 // Connection creation
2039 saddrlen = sizeof(struct sockaddr_storage);
2040
2041 socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen);
2042
2043 if (socktemp == INVALID_SOCKET)
2044 {
2045 sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
2046 rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
2047 errbuf);
2048 goto error;
2049 }
2050
2051 // Now that I accepted the connection, the server socket is no longer needed
2052 sock_close(session->sockdata, NULL, 0);
2053 session->sockdata = socktemp;
2054 }
2055
2056 SSL *ssl = NULL;
2057 if (uses_ssl)
2058 {
2059 #ifdef HAVE_OPENSSL
2060 /* In both active or passive cases, wait for the client to initiate the
2061 * TLS handshake. Yes during that time the control socket will not be
2062 * served, but the same was true from the above call to accept(). */
2063 ssl = ssl_promotion(1, session->sockdata, errbuf, PCAP_ERRBUF_SIZE);
2064 if (! ssl)
2065 {
2066 rpcapd_log(LOGPRIO_ERROR, "TLS handshake failed: %s", errbuf);
2067 goto error;
2068 }
2069 #endif
2070 }
2071 session->data_ssl = ssl;
2072
2073 // Now we have to create a new thread to receive packets
2074 #ifdef _WIN32
2075 session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
2076 (void *) session, 0, NULL);
2077 if (session->thread == 0)
2078 {
2079 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
2080 goto error;
2081 }
2082 #else
2083 ret = pthread_create(&session->thread, NULL, daemon_thrdatamain,
2084 (void *) session);
2085 if (ret != 0)
2086 {
2087 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2088 ret, "Error creating the data thread");
2089 goto error;
2090 }
2091 #endif
2092 session->have_thread = 1;
2093
2094 // Check if all the data has been read; if not, discard the data in excess
2095 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2096 goto fatal_error;
2097
2098 *sessionp = session;
2099 return 0;
2100
2101 error:
2102 //
2103 // Not a fatal error, so send the client an error message and
2104 // keep serving client requests.
2105 //
2106 *sessionp = NULL;
2107
2108 if (addrinfo)
2109 freeaddrinfo(addrinfo);
2110
2111 if (session)
2112 {
2113 session_close(session);
2114 free(session);
2115 }
2116
2117 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver,
2118 PCAP_ERR_STARTCAPTURE, errmsgbuf, errbuf) == -1)
2119 {
2120 // That failed; log a message and give up.
2121 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2122 return -1;
2123 }
2124
2125 // Check if all the data has been read; if not, discard the data in excess
2126 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2127 {
2128 // Network error.
2129 return -1;
2130 }
2131
2132 return 0;
2133
2134 fatal_error:
2135 //
2136 // Fatal network error, so don't try to communicate with
2137 // the client, just give up.
2138 //
2139 *sessionp = NULL;
2140
2141 if (session)
2142 {
2143 session_close(session);
2144 free(session);
2145 }
2146
2147 return -1;
2148 }
2149
2150 static int
2151 daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars,
2152 struct session *session)
2153 {
2154 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2155 struct rpcap_header header;
2156
2157 session_close(session);
2158
2159 rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0);
2160
2161 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2162 {
2163 // That failed; log a message and give up.
2164 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2165 return -1;
2166 }
2167
2168 return 0;
2169 }
2170
2171 static int
2172 daemon_unpackapplyfilter(SOCKET sockctrl, SSL *ctrl_ssl, struct session *session, uint32 *plenp, char *errmsgbuf)
2173 {
2174 int status;
2175 struct rpcap_filter filter;
2176 struct rpcap_filterbpf_insn insn;
2177 struct bpf_insn *bf_insn;
2178 struct bpf_program bf_prog;
2179 unsigned int i;
2180
2181 status = rpcapd_recv(sockctrl, ctrl_ssl, (char *) &filter,
2182 sizeof(struct rpcap_filter), plenp, errmsgbuf);
2183 if (status == -1)
2184 {
2185 return -1;
2186 }
2187 if (status == -2)
2188 {
2189 return -2;
2190 }
2191
2192 bf_prog.bf_len = ntohl(filter.nitems);
2193
2194 if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
2195 {
2196 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
2197 return -2;
2198 }
2199
2200 bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
2201 if (bf_insn == NULL)
2202 {
2203 pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
2204 errno, "malloc() failed");
2205 return -2;
2206 }
2207
2208 bf_prog.bf_insns = bf_insn;
2209
2210 for (i = 0; i < bf_prog.bf_len; i++)
2211 {
2212 status = rpcapd_recv(sockctrl, ctrl_ssl, (char *) &insn,
2213 sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
2214 if (status == -1)
2215 {
2216 return -1;
2217 }
2218 if (status == -2)
2219 {
2220 return -2;
2221 }
2222
2223 bf_insn->code = ntohs(insn.code);
2224 bf_insn->jf = insn.jf;
2225 bf_insn->jt = insn.jt;
2226 bf_insn->k = ntohl(insn.k);
2227
2228 bf_insn++;
2229 }
2230
2231 //
2232 // XXX - pcap_setfilter() should do the validation for us.
2233 //
2234 if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
2235 {
2236 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
2237 return -2;
2238 }
2239
2240 if (pcap_setfilter(session->fp, &bf_prog))
2241 {
2242 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
2243 return -2;
2244 }
2245
2246 return 0;
2247 }
2248
2249 static int
2250 daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars,
2251 struct session *session, uint32 plen)
2252 {
2253 char errbuf[PCAP_ERRBUF_SIZE];
2254 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2255 int ret; // status of daemon_unpackapplyfilter()
2256 struct rpcap_header header; // keeps the answer to the updatefilter command
2257
2258 ret = daemon_unpackapplyfilter(pars->sockctrl, pars->ssl, session, &plen, errmsgbuf);
2259 if (ret == -1)
2260 {
2261 // Fatal error. A message has been logged; just give up.
2262 return -1;
2263 }
2264 if (ret == -2)
2265 {
2266 // Non-fatal error. Send an error reply to the client.
2267 goto error;
2268 }
2269
2270 // Check if all the data has been read; if not, discard the data in excess
2271 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2272 {
2273 // Network error.
2274 return -1;
2275 }
2276
2277 // A response is needed, otherwise the other host does not know that everything went well
2278 rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
2279
2280 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
2281 {
2282 // That failed; log a messsage and give up.
2283 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2284 return -1;
2285 }
2286
2287 return 0;
2288
2289 error:
2290 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2291 {
2292 return -1;
2293 }
2294 rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_UPDATEFILTER,
2295 errmsgbuf, NULL);
2296
2297 return 0;
2298 }
2299
2300 /*!
2301 \brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
2302 */
2303 static int
2304 daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen,
2305 struct rpcap_sampling *samp_param)
2306 {
2307 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2308 char errmsgbuf[PCAP_ERRBUF_SIZE];
2309 struct rpcap_header header;
2310 struct rpcap_sampling rpcap_samp;
2311 int status;
2312
2313 status = rpcapd_recv(pars->sockctrl, pars->ssl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
2314 if (status == -1)
2315 {
2316 return -1;
2317 }
2318 if (status == -2)
2319 {
2320 goto error;
2321 }
2322
2323 // Save these settings in the pcap_t
2324 samp_param->method = rpcap_samp.method;
2325 samp_param->value = ntohl(rpcap_samp.value);
2326
2327 // A response is needed, otherwise the other host does not know that everything went well
2328 rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
2329
2330 if (sock_send(pars->sockctrl, pars->ssl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2331 {
2332 // That failed; log a messsage and give up.
2333 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2334 return -1;
2335 }
2336
2337 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2338 {
2339 return -1;
2340 }
2341
2342 return 0;
2343
2344 error:
2345 if (rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_SETSAMPLING,
2346 errmsgbuf, errbuf) == -1)
2347 {
2348 // That failed; log a message and give up.
2349 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2350 return -1;
2351 }
2352
2353 // Check if all the data has been read; if not, discard the data in excess
2354 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2355 {
2356 return -1;
2357 }
2358
2359 return 0;
2360 }
2361
2362 static int
2363 daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars,
2364 struct session *session, uint32 plen, struct pcap_stat *stats,
2365 unsigned int svrcapt)
2366 {
2367 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2368 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2369 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
2370 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
2371 struct rpcap_stats *netstats; // statistics sent on the network
2372
2373 // Checks that the header does not contain other data; if so, discard it
2374 if (rpcapd_discard(pars->sockctrl, pars->ssl, plen) == -1)
2375 {
2376 // Network error.
2377 return -1;
2378 }
2379
2380 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2381 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2382 goto error;
2383
2384 rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
2385 RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
2386
2387 netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
2388
2389 if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
2390 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2391 goto error;
2392
2393 if (session && session->fp)
2394 {
2395 if (pcap_stats(session->fp, stats) == -1)
2396 {
2397 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
2398 goto error;
2399 }
2400
2401 netstats->ifdrop = htonl(stats->ps_ifdrop);
2402 netstats->ifrecv = htonl(stats->ps_recv);
2403 netstats->krnldrop = htonl(stats->ps_drop);
2404 netstats->svrcapt = htonl(session->TotCapt);
2405 }
2406 else
2407 {
2408 // We have to keep compatibility with old applications,
2409 // which ask for statistics also when the capture has
2410 // already stopped.
2411 netstats->ifdrop = htonl(stats->ps_ifdrop);
2412 netstats->ifrecv = htonl(stats->ps_recv);
2413 netstats->krnldrop = htonl(stats->ps_drop);
2414 netstats->svrcapt = htonl(svrcapt);
2415 }
2416
2417 // Send the packet
2418 if (sock_send(pars->sockctrl, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
2419 {
2420 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2421 return -1;
2422 }
2423
2424 return 0;
2425
2426 error:
2427 rpcap_senderror(pars->sockctrl, pars->ssl, ver, PCAP_ERR_GETSTATS,
2428 errmsgbuf, NULL);
2429 return 0;
2430 }
2431
2432 #ifdef _WIN32
2433 static unsigned __stdcall
2434 #else
2435 static void *
2436 #endif
2437 daemon_thrdatamain(void *ptr)
2438 {
2439 char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
2440 struct session *session; // pointer to the struct session for this session
2441 int retval; // general variable used to keep the return value of other functions
2442 struct rpcap_pkthdr *net_pkt_header;// header of the packet
2443 struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
2444 u_char *pkt_data; // pointer to the buffer that contains the current packet
2445 size_t sendbufsize; // size for the send buffer
2446 char *sendbuf; // temporary buffer in which data to be sent is buffered
2447 int sendbufidx; // index which keeps the number of bytes currently buffered
2448 int status;
2449 #ifndef _WIN32
2450 sigset_t sigusr1; // signal set with just SIGUSR1
2451 #endif
2452
2453 session = (struct session *) ptr;
2454
2455 session->TotCapt = 0; // counter which is incremented each time a packet is received
2456
2457 // Initialize errbuf
2458 memset(errbuf, 0, sizeof(errbuf));
2459
2460 //
2461 // We need a buffer large enough to hold a buffer large enough
2462 // for a maximum-size packet for this pcap_t.
2463 //
2464 if (pcap_snapshot(session->fp) < 0)
2465 {
2466 //
2467 // The snapshot length is negative.
2468 // This "should not happen".
2469 //
2470 rpcapd_log(LOGPRIO_ERROR,
2471 "Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
2472 pcap_snapshot(session->fp));
2473 sendbuf = NULL; // we can't allocate a buffer, so nothing to free
2474 goto error;
2475 }
2476 //
2477 // size_t is unsigned, and the result of pcap_snapshot() is signed;
2478 // on no platform that we support is int larger than size_t.
2479 // This means that, unless the extra information we prepend to
2480 // a maximum-sized packet is impossibly large, the sum of the
2481 // snapshot length and the size of that extra information will
2482 // fit in a size_t.
2483 //
2484 // So we don't need to make sure that sendbufsize will overflow.
2485 //
2486 // However, we *do* need to make sure its value fits in an int,
2487 // because sock_send() can't send more than INT_MAX bytes (it could
2488 // do so on 64-bit UN*Xes, but can't do so on Windows, not even
2489 // 64-bit Windows, as the send() buffer size argument is an int
2490 // in Winsock).
2491 //
2492 sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
2493 if (sendbufsize > INT_MAX)
2494 {
2495 rpcapd_log(LOGPRIO_ERROR,
2496 "Buffer size for this child thread would be larger than %d",
2497 INT_MAX);
2498 sendbuf = NULL; // we haven't allocated a buffer, so nothing to free
2499 goto error;
2500 }
2501 sendbuf = (char *) malloc (sendbufsize);
2502 if (sendbuf == NULL)
2503 {
2504 rpcapd_log(LOGPRIO_ERROR,
2505 "Unable to allocate the buffer for this child thread");
2506 goto error;
2507 }
2508
2509 #ifndef _WIN32
2510 //
2511 // Set the signal set to include just SIGUSR1, and block that
2512 // signal; we only want it unblocked when we're reading
2513 // packets - we dn't want any other system calls, such as
2514 // ones being used to send to the client or to log messages,
2515 // to be interrupted.
2516 //
2517 sigemptyset(&sigusr1);
2518 sigaddset(&sigusr1, SIGUSR1);
2519 pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
2520 #endif
2521
2522 // Retrieve the packets
2523 for (;;)
2524 {
2525 #ifndef _WIN32
2526 //
2527 // Unblock SIGUSR1 while we might be waiting for packets.
2528 //
2529 pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL);
2530 #endif
2531 retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning
2532 #ifndef _WIN32
2533 //
2534 // Now block it again.
2535 //
2536 pthread_sigmask(SIG_BLOCK, &sigusr1, NULL);
2537 #endif
2538 if (retval < 0)
2539 break; // error
2540 if (retval == 0) // Read timeout elapsed
2541 continue;
2542
2543 sendbufidx = 0;
2544
2545 // Bufferize the general header
2546 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2547 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2548 PCAP_ERRBUF_SIZE) == -1)
2549 {
2550 rpcapd_log(LOGPRIO_ERROR,
2551 "sock_bufferize() error sending packet message: %s",
2552 errbuf);
2553 goto error;
2554 }
2555
2556 rpcap_createhdr((struct rpcap_header *) sendbuf,
2557 session->protocol_version, RPCAP_MSG_PACKET, 0,
2558 (uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
2559
2560 net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
2561
2562 // Bufferize the pkt header
2563 if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
2564 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2565 PCAP_ERRBUF_SIZE) == -1)
2566 {
2567 rpcapd_log(LOGPRIO_ERROR,
2568 "sock_bufferize() error sending packet message: %s",
2569 errbuf);
2570 goto error;
2571 }
2572
2573 net_pkt_header->caplen = htonl(pkt_header->caplen);
2574 net_pkt_header->len = htonl(pkt_header->len);
2575 net_pkt_header->npkt = htonl(++(session->TotCapt));
2576 //
2577 // This protocol needs to be updated with a new version
2578 // before 2038-01-19 03:14:07 UTC.
2579 //
2580 net_pkt_header->timestamp_sec = htonl((uint32)pkt_header->ts.tv_sec);
2581 net_pkt_header->timestamp_usec = htonl((uint32)pkt_header->ts.tv_usec);
2582
2583 // Bufferize the pkt data
2584 if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
2585 sendbuf, &sendbufidx, (int)sendbufsize, SOCKBUF_BUFFERIZE,
2586 errbuf, PCAP_ERRBUF_SIZE) == -1)
2587 {
2588 rpcapd_log(LOGPRIO_ERROR,
2589 "sock_bufferize() error sending packet message: %s",
2590 errbuf);
2591 goto error;
2592 }
2593
2594 // Send the packet
2595 // If the client dropped the connection, don't report an
2596 // error, just quit.
2597 status = sock_send(session->sockdata, session->data_ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
2598 if (status < 0)
2599 {
2600 if (status == -1)
2601 {
2602 //
2603 // Error other than "client closed the
2604 // connection out from under us"; report
2605 // it.
2606 //
2607 rpcapd_log(LOGPRIO_ERROR,
2608 "Send of packet to client failed: %s",
2609 errbuf);
2610 }
2611
2612 //
2613 // Give up in either case.
2614 //
2615 goto error;
2616 }
2617 }
2618
2619 if (retval < 0 && retval != PCAP_ERROR_BREAK)
2620 {
2621 //
2622 // Failed with an error other than "we were told to break
2623 // out of the loop".
2624 //
2625 // The latter just means that the client told us to stop
2626 // capturing, so there's no error to report.
2627 //
2628 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
2629 rpcap_senderror(session->sockctrl, session->ctrl_ssl, session->protocol_version,
2630 PCAP_ERR_READEX, errbuf, NULL);
2631 }
2632
2633 error:
2634 //
2635 // The main thread will clean up the session structure.
2636 //
2637 free(sendbuf);
2638
2639 return 0;
2640 }
2641
2642 #ifndef _WIN32
2643 //
2644 // Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to
2645 // interrupt the data thread if it's blocked in a system call waiting
2646 // for packets to arrive.
2647 //
2648 static void noop_handler(int sign _U_)
2649 {
2650 }
2651 #endif
2652
2653 /*!
2654 \brief It serializes a network address.
2655
2656 It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
2657 that can be used to be sent on the network. Basically, it applies all the hton()
2658 conversion required to the input variable.
2659
2660 \param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
2661 serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
2662
2663 \param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
2664 the serialized data. This variable has to be allocated by the user.
2665
2666 \warning This function supports only AF_INET and AF_INET6 address families.
2667 */
2668 static void
2669 daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
2670 {
2671 memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
2672
2673 // There can be the case in which the sockaddrin is not available
2674 if (sockaddrin == NULL) return;
2675
2676 // Warning: we support only AF_INET and AF_INET6
2677 switch (sockaddrin->ss_family)
2678 {
2679 case AF_INET:
2680 {
2681 struct sockaddr_in *sockaddrin_ipv4;
2682 struct rpcap_sockaddr_in *sockaddrout_ipv4;
2683
2684 sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
2685 sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
2686 sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
2687 sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
2688 memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
2689 memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
2690 break;
2691 }
2692
2693 #ifdef AF_INET6
2694 case AF_INET6:
2695 {
2696 struct sockaddr_in6 *sockaddrin_ipv6;
2697 struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
2698
2699 sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
2700 sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
2701 sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
2702 sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
2703 sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
2704 memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
2705 sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
2706 break;
2707 }
2708 #endif
2709 }
2710 }
2711
2712
2713 /*!
2714 \brief Suspends a thread for secs seconds.
2715 */
2716 void sleep_secs(int secs)
2717 {
2718 #ifdef _WIN32
2719 Sleep(secs*1000);
2720 #else
2721 unsigned secs_remaining;
2722
2723 if (secs <= 0)
2724 return;
2725 secs_remaining = secs;
2726 while (secs_remaining != 0)
2727 secs_remaining = sleep(secs_remaining);
2728 #endif
2729 }
2730
2731 /*
2732 * Read the header of a message.
2733 */
2734 static int
2735 rpcapd_recv_msg_header(SOCKET sock, SSL *ssl, struct rpcap_header *headerp)
2736 {
2737 int nread;
2738 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2739
2740 nread = sock_recv(sock, ssl, (char *) headerp, sizeof(struct rpcap_header),
2741 SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2742 if (nread == -1)
2743 {
2744 // Network error.
2745 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2746 return -1;
2747 }
2748 if (nread == 0)
2749 {
2750 // Immediate EOF; that's treated like a close message.
2751 return -2;
2752 }
2753 headerp->plen = ntohl(headerp->plen);
2754 return 0;
2755 }
2756
2757 /*
2758 * Read data from a message.
2759 * If we're trying to read more data that remains, puts an error
2760 * message into errmsgbuf and returns -2. Otherwise, tries to read
2761 * the data and, if that succeeds, subtracts the amount read from
2762 * the number of bytes of data that remains.
2763 * Returns 0 on success, logs a message and returns -1 on a network
2764 * error.
2765 */
2766 static int
2767 rpcapd_recv(SOCKET sock, SSL *ssl, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
2768 {
2769 int nread;
2770 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2771
2772 if (toread > *plen)
2773 {
2774 // Tell the client and continue.
2775 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
2776 return -2;
2777 }
2778 nread = sock_recv(sock, ssl, buffer, toread,
2779 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2780 if (nread == -1)
2781 {
2782 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2783 return -1;
2784 }
2785 *plen -= nread;
2786 return 0;
2787 }
2788
2789 /*
2790 * Discard data from a connection.
2791 * Mostly used to discard wrong-sized messages.
2792 * Returns 0 on success, logs a message and returns -1 on a network
2793 * error.
2794 */
2795 static int
2796 rpcapd_discard(SOCKET sock, SSL *ssl, uint32 len)
2797 {
2798 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
2799
2800 if (len != 0)
2801 {
2802 if (sock_discard(sock, ssl, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
2803 {
2804 // Network error.
2805 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2806 return -1;
2807 }
2808 }
2809 return 0;
2810 }
2811
2812 //
2813 // Shut down any packet-capture thread associated with the session,
2814 // close the SSL handle for the data socket if we have one, close
2815 // the data socket if we have one, and close the underlying packet
2816 // capture handle if we have one.
2817 //
2818 // We do not, of course, touch the controlling socket that's also
2819 // copied into the session, as the service loop might still use it.
2820 //
2821 static void session_close(struct session *session)
2822 {
2823 if (session->have_thread)
2824 {
2825 //
2826 // Tell the data connection thread main capture loop to
2827 // break out of that loop.
2828 //
2829 // This may be sufficient to wake up a blocked thread,
2830 // but it's not guaranteed to be sufficient.
2831 //
2832 pcap_breakloop(session->fp);
2833
2834 #ifdef _WIN32
2835 //
2836 // Set the event on which a read would block, so that,
2837 // if it's currently blocked waiting for packets to
2838 // arrive, it'll wake up, so it can see the "break
2839 // out of the loop" indication. (pcap_breakloop()
2840 // might do this, but older versions don't. Setting
2841 // it twice should, at worst, cause an extra wakeup,
2842 // which shouldn't be a problem.)
2843 //
2844 // XXX - what about modules other than NPF?
2845 //
2846 SetEvent(pcap_getevent(session->fp));
2847
2848 //
2849 // Wait for the thread to exit, so we don't close
2850 // sockets out from under it.
2851 //
2852 // XXX - have a timeout, so we don't wait forever?
2853 //
2854 WaitForSingleObject(session->thread, INFINITE);
2855
2856 //
2857 // Release the thread handle, as we're done with
2858 // it.
2859 //
2860 CloseHandle(session->thread);
2861 session->have_thread = 0;
2862 session->thread = INVALID_HANDLE_VALUE;
2863 #else
2864 //
2865 // Send a SIGUSR1 signal to the thread, so that, if
2866 // it's currently blocked waiting for packets to arrive,
2867 // it'll wake up (we've turned off SA_RESTART for
2868 // SIGUSR1, so that the system call in which it's blocked
2869 // should return EINTR rather than restarting).
2870 //
2871 pthread_kill(session->thread, SIGUSR1);
2872
2873 //
2874 // Wait for the thread to exit, so we don't close
2875 // sockets out from under it.
2876 //
2877 // XXX - have a timeout, so we don't wait forever?
2878 //
2879 pthread_join(session->thread, NULL);
2880 session->have_thread = 0;
2881 memset(&session->thread, 0, sizeof(session->thread));
2882 #endif
2883 }
2884
2885 #ifdef HAVE_OPENSSL
2886 if (session->data_ssl)
2887 {
2888 // Finish using the SSL handle for the socket.
2889 // This must be done *before* the socket is closed.
2890 ssl_finish(session->data_ssl);
2891 session->data_ssl = NULL;
2892 }
2893 #endif
2894
2895 if (session->sockdata != INVALID_SOCKET)
2896 {
2897 sock_close(session->sockdata, NULL, 0);
2898 session->sockdata = INVALID_SOCKET;
2899 }
2900
2901 if (session->fp)
2902 {
2903 pcap_close(session->fp);
2904 session->fp = NULL;
2905 }
2906 }