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