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