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