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