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