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