]> The Tcpdump Group git mirrors - libpcap/blob - pcap-rpcap.c
Make sure no read routine process more than INT_MAX packets.
[libpcap] / pcap-rpcap.c
1 /*
2 * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
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, CACE Technologies
16 * nor the names of its contributors may be used to endorse or promote
17 * products derived from this software without specific prior written
18 * permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #include "ftmacros.h"
39 #include "diag-control.h"
40
41 #include <string.h> /* for strlen(), ... */
42 #include <stdlib.h> /* for malloc(), free(), ... */
43 #include <stdarg.h> /* for functions with variable number of arguments */
44 #include <errno.h> /* for the errno variable */
45 #include <limits.h> /* for INT_MAX */
46 #include "sockutils.h"
47 #include "pcap-int.h"
48 #include "rpcap-protocol.h"
49 #include "pcap-rpcap.h"
50
51 #ifdef _WIN32
52 #include "charconv.h" /* for utf_8_to_acp_truncated() */
53 #endif
54
55 #ifdef HAVE_OPENSSL
56 #include "sslutils.h"
57 #endif
58
59 /*
60 * This file contains the pcap module for capturing from a remote machine's
61 * interfaces using the RPCAP protocol.
62 *
63 * WARNING: All the RPCAP functions that are allowed to return a buffer
64 * containing the error description can return max PCAP_ERRBUF_SIZE characters.
65 * However there is no guarantees that the string will be zero-terminated.
66 * Best practice is to define the errbuf variable as a char of size
67 * 'PCAP_ERRBUF_SIZE+1' and to insert manually a NULL character at the end
68 * of the buffer. This will guarantee that no buffer overflows occur even
69 * if we use the printf() to show the error on the screen.
70 *
71 * XXX - actually, null-terminating the error string is part of the
72 * contract for the pcap API; if there's any place in the pcap code
73 * that doesn't guarantee null-termination, even at the expense of
74 * cutting the message short, that's a bug and needs to be fixed.
75 */
76
77 #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
78 #ifdef _WIN32
79 #define PCAP_STATS_EX 1 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
80 #endif
81
82 /*
83 * \brief Keeps a list of all the opened connections in the active mode.
84 *
85 * This structure defines a linked list of items that are needed to keep the info required to
86 * manage the active mode.
87 * In other words, when a new connection in active mode starts, this structure is updated so that
88 * it reflects the list of active mode connections currently opened.
89 * This structure is required by findalldevs() and open_remote() to see if they have to open a new
90 * control connection toward the host, or they already have a control connection in place.
91 */
92 struct activehosts
93 {
94 struct sockaddr_storage host;
95 SOCKET sockctrl;
96 SSL *ssl;
97 uint8 protocol_version;
98 struct activehosts *next;
99 };
100
101 /* Keeps a list of all the opened connections in the active mode. */
102 static struct activehosts *activeHosts;
103
104 /*
105 * Keeps the main socket identifier when we want to accept a new remote
106 * connection (active mode only).
107 * See the documentation of pcap_remoteact_accept() and
108 * pcap_remoteact_cleanup() for more details.
109 */
110 static SOCKET sockmain;
111 static SSL *ssl_main;
112
113 /*
114 * Private data for capturing remotely using the rpcap protocol.
115 */
116 struct pcap_rpcap {
117 /*
118 * This is '1' if we're the network client; it is needed by several
119 * functions (such as pcap_setfilter()) to know whether they have
120 * to use the socket or have to open the local adapter.
121 */
122 int rmt_clientside;
123
124 SOCKET rmt_sockctrl; /* socket ID of the socket used for the control connection */
125 SOCKET rmt_sockdata; /* socket ID of the socket used for the data connection */
126 SSL *ctrl_ssl, *data_ssl; /* optional transport of rmt_sockctrl and rmt_sockdata via TLS */
127 int rmt_flags; /* we have to save flags, since they are passed by the pcap_open_live(), but they are used by the pcap_startcapture() */
128 int rmt_capstarted; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
129 char *currentfilter; /* Pointer to a buffer (allocated at run-time) that stores the current filter. Needed when flag PCAP_OPENFLAG_NOCAPTURE_RPCAP is turned on. */
130
131 uint8 protocol_version; /* negotiated protocol version */
132 uint8 uses_ssl; /* User asked for rpcaps scheme */
133
134 unsigned int TotNetDrops; /* keeps the number of packets that have been dropped by the network */
135
136 /*
137 * This keeps the number of packets that have been received by the
138 * application.
139 *
140 * Packets dropped by the kernel buffer are not counted in this
141 * variable. It is always equal to (TotAccepted - TotDrops),
142 * except for the case of remote capture, in which we have also
143 * packets in flight, i.e. that have been transmitted by the remote
144 * host, but that have not been received (yet) from the client.
145 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
146 * wrong result, since this number does not corresponds always to
147 * the number of packet received by the application. For this reason,
148 * in the remote capture we need another variable that takes into
149 * account of the number of packets actually received by the
150 * application.
151 */
152 unsigned int TotCapt;
153
154 struct pcap_stat stat;
155 /* XXX */
156 struct pcap *next; /* list of open pcaps that need stuff cleared on close */
157 };
158
159 /****************************************************
160 * *
161 * Locally defined functions *
162 * *
163 ****************************************************/
164 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode);
165 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
166 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
167 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
168 static void pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter);
169 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog);
170 static int pcap_setsampling_remote(pcap_t *fp);
171 static int pcap_startcapture_remote(pcap_t *fp);
172 static int rpcap_recv_msg_header(SOCKET sock, SSL *, struct rpcap_header *header, char *errbuf);
173 static int rpcap_check_msg_ver(SOCKET sock, SSL *, uint8 expected_ver, struct rpcap_header *header, char *errbuf);
174 static int rpcap_check_msg_type(SOCKET sock, SSL *, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf);
175 static int rpcap_process_msg_header(SOCKET sock, SSL *, uint8 ver, uint8 request_type, struct rpcap_header *header, char *errbuf);
176 static int rpcap_recv(SOCKET sock, SSL *, void *buffer, size_t toread, uint32 *plen, char *errbuf);
177 static void rpcap_msg_err(SOCKET sockctrl, SSL *, uint32 plen, char *remote_errbuf);
178 static int rpcap_discard(SOCKET sock, SSL *, uint32 len, char *errbuf);
179 static int rpcap_read_packet_msg(struct pcap_rpcap const *, pcap_t *p, size_t size);
180
181 /****************************************************
182 * *
183 * Function bodies *
184 * *
185 ****************************************************/
186
187 /*
188 * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
189 * structure from the network byte order to a 'sockaddr_in" or
190 * 'sockaddr_in6' structure in the host byte order.
191 *
192 * It accepts an 'rpcap_sockaddr' structure as it is received from the
193 * network, and checks the address family field against various values
194 * to see whether it looks like an IPv4 address, an IPv6 address, or
195 * neither of those. It checks for multiple values in order to try
196 * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
197 * or 'sockaddr_in6' structures over the wire with some members
198 * byte-swapped, and to handle the fact that AF_INET6 has different
199 * values on different OSes.
200 *
201 * For IPv4 addresses, it converts the address family to host byte
202 * order from network byte order and puts it into the structure,
203 * sets the length if a sockaddr structure has a length, converts the
204 * port number to host byte order from network byte order and puts
205 * it into the structure, copies over the IPv4 address, and zeroes
206 * out the zero padding.
207 *
208 * For IPv6 addresses, it converts the address family to host byte
209 * order from network byte order and puts it into the structure,
210 * sets the length if a sockaddr structure has a length, converts the
211 * port number and flow information to host byte order from network
212 * byte order and puts them into the structure, copies over the IPv6
213 * address, and converts the scope ID to host byte order from network
214 * byte order and puts it into the structure.
215 *
216 * The function will allocate the 'sockaddrout' variable according to the
217 * address family in use. In case the address does not belong to the
218 * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
219 * NULL pointer is returned. This usually happens because that address
220 * does not exist on the other host, or is of an address family other
221 * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
222 * structure containing all 'zero' values.
223 *
224 * Older RPCAPDs sent the addresses over the wire in the OS's native
225 * structure format. For most OSes, this looks like the over-the-wire
226 * format, but might have a different value for AF_INET6 than the value
227 * on the machine receiving the reply. For OSes with the newer BSD-style
228 * sockaddr structures, this has, instead of a 2-byte address family,
229 * a 1-byte structure length followed by a 1-byte address family. The
230 * RPCAPD code would put the address family in network byte order before
231 * sending it; that would set it to 0 on a little-endian machine, as
232 * htons() of any value between 1 and 255 would result in a value > 255,
233 * with its lower 8 bits zero, so putting that back into a 1-byte field
234 * would set it to 0.
235 *
236 * Therefore, for older RPCAPDs running on an OS with newer BSD-style
237 * sockaddr structures, the family field, if treated as a big-endian
238 * (network byte order) 16-bit field, would be:
239 *
240 * (length << 8) | family if sent by a big-endian machine
241 * (length << 8) if sent by a little-endian machine
242 *
243 * For current RPCAPDs, and for older RPCAPDs running on an OS with
244 * older BSD-style sockaddr structures, the family field, if treated
245 * as a big-endian 16-bit field, would just contain the family.
246 *
247 * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
248 * to be de-serialized.
249 *
250 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
251 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
252 * This variable will be allocated automatically inside this function.
253 *
254 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
255 * that will contain the error message (in case there is one).
256 *
257 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
258 * can be only the fact that the malloc() failed to allocate memory.
259 * The error message is returned in the 'errbuf' variable, while the deserialized address
260 * is returned into the 'sockaddrout' variable.
261 *
262 * \warning This function supports only AF_INET and AF_INET6 address families.
263 *
264 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
265 */
266
267 /*
268 * Possible IPv4 family values other than the designated over-the-wire value,
269 * which is 2 (because everybody uses 2 for AF_INET4).
270 */
271 #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
272 #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
273 #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
274 #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
275
276 /*
277 * Possible IPv6 family values other than the designated over-the-wire value,
278 * which is 23 (because that's what Windows uses, and most RPCAP servers
279 * out there are probably running Windows, as WinPcap includes the server
280 * but few if any UN*Xes build and ship it).
281 *
282 * The new BSD sockaddr structure format was in place before 4.4-Lite, so
283 * all the free-software BSDs use it.
284 */
285 #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
286 #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
287 #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
288 #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
289 #define LINUX_AF_INET6 10
290 #define HPUX_AF_INET6 22
291 #define AIX_AF_INET6 24
292 #define SOLARIS_AF_INET6 26
293
294 static int
295 rpcap_deseraddr(struct rpcap_sockaddr *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
296 {
297 /* Warning: we support only AF_INET and AF_INET6 */
298 switch (ntohs(sockaddrin->family))
299 {
300 case RPCAP_AF_INET:
301 case NEW_BSD_AF_INET_BE:
302 case NEW_BSD_AF_INET_LE:
303 {
304 struct rpcap_sockaddr_in *sockaddrin_ipv4;
305 struct sockaddr_in *sockaddrout_ipv4;
306
307 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
308 if ((*sockaddrout) == NULL)
309 {
310 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
311 errno, "malloc() failed");
312 return -1;
313 }
314 sockaddrin_ipv4 = (struct rpcap_sockaddr_in *) sockaddrin;
315 sockaddrout_ipv4 = (struct sockaddr_in *) (*sockaddrout);
316 sockaddrout_ipv4->sin_family = AF_INET;
317 sockaddrout_ipv4->sin_port = ntohs(sockaddrin_ipv4->port);
318 memcpy(&sockaddrout_ipv4->sin_addr, &sockaddrin_ipv4->addr, sizeof(sockaddrout_ipv4->sin_addr));
319 memset(sockaddrout_ipv4->sin_zero, 0, sizeof(sockaddrout_ipv4->sin_zero));
320 break;
321 }
322
323 #ifdef AF_INET6
324 case RPCAP_AF_INET6:
325 case NEW_BSD_AF_INET6_BSD_BE:
326 case NEW_BSD_AF_INET6_FREEBSD_BE:
327 case NEW_BSD_AF_INET6_DARWIN_BE:
328 case NEW_BSD_AF_INET6_LE:
329 case LINUX_AF_INET6:
330 case HPUX_AF_INET6:
331 case AIX_AF_INET6:
332 case SOLARIS_AF_INET6:
333 {
334 struct rpcap_sockaddr_in6 *sockaddrin_ipv6;
335 struct sockaddr_in6 *sockaddrout_ipv6;
336
337 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
338 if ((*sockaddrout) == NULL)
339 {
340 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
341 errno, "malloc() failed");
342 return -1;
343 }
344 sockaddrin_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrin;
345 sockaddrout_ipv6 = (struct sockaddr_in6 *) (*sockaddrout);
346 sockaddrout_ipv6->sin6_family = AF_INET6;
347 sockaddrout_ipv6->sin6_port = ntohs(sockaddrin_ipv6->port);
348 sockaddrout_ipv6->sin6_flowinfo = ntohl(sockaddrin_ipv6->flowinfo);
349 memcpy(&sockaddrout_ipv6->sin6_addr, &sockaddrin_ipv6->addr, sizeof(sockaddrout_ipv6->sin6_addr));
350 sockaddrout_ipv6->sin6_scope_id = ntohl(sockaddrin_ipv6->scope_id);
351 break;
352 }
353 #endif
354
355 default:
356 /*
357 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
358 * support AF_INET6, it's not AF_INET).
359 */
360 *sockaddrout = NULL;
361 break;
362 }
363 return 0;
364 }
365
366 /*
367 * This function reads a packet from the network socket. It does not
368 * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
369 * the "nocb" string into its name).
370 *
371 * This function is called by pcap_read_rpcap().
372 *
373 * WARNING: By choice, this function does not make use of semaphores. A smarter
374 * implementation should put a semaphore into the data thread, and a signal will
375 * be raised as soon as there is data into the socket buffer.
376 * However this is complicated and it does not bring any advantages when reading
377 * from the network, in which network delays can be much more important than
378 * these optimizations. Therefore, we chose the following approach:
379 * - the 'timeout' chosen by the user is split in two (half on the server side,
380 * with the usual meaning, and half on the client side)
381 * - this function checks for packets; if there are no packets, it waits for
382 * timeout/2 and then it checks again. If packets are still missing, it returns,
383 * otherwise it reads packets.
384 */
385 static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr *pkt_header, u_char **pkt_data)
386 {
387 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
388 struct rpcap_header *header; /* general header according to the RPCAP format */
389 struct rpcap_pkthdr *net_pkt_header; /* header of the packet, from the message */
390 u_char *net_pkt_data; /* packet data from the message */
391 uint32 plen;
392 int retval = 0; /* generic return value */
393 int msglen;
394
395 /* Structures needed for the select() call */
396 struct timeval tv; /* maximum time the select() can block waiting for data */
397 fd_set rfds; /* set of socket descriptors we have to check */
398
399 /*
400 * Define the packet buffer timeout, to be used in the select()
401 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
402 */
403 tv.tv_sec = p->opt.timeout / 1000;
404 tv.tv_usec = (suseconds_t)((p->opt.timeout - tv.tv_sec * 1000) * 1000);
405
406 #ifdef HAVE_OPENSSL
407 /* Check if we still have bytes available in the last decoded TLS record.
408 * If that's the case, we know SSL_read will not block. */
409 retval = pr->data_ssl && SSL_pending(pr->data_ssl) > 0;
410 #endif
411 if (! retval)
412 {
413 /* Watch out sockdata to see if it has input */
414 FD_ZERO(&rfds);
415
416 /*
417 * 'fp->rmt_sockdata' has always to be set before calling the select(),
418 * since it is cleared by the select()
419 */
420 FD_SET(pr->rmt_sockdata, &rfds);
421
422 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
423 retval = 1;
424 #else
425 retval = select((int) pr->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
426 #endif
427
428 if (retval == -1)
429 {
430 #ifndef _WIN32
431 if (errno == EINTR)
432 {
433 /* Interrupted. */
434 return 0;
435 }
436 #endif
437 sock_geterror("select()", p->errbuf, PCAP_ERRBUF_SIZE);
438 return -1;
439 }
440 }
441
442 /* There is no data waiting, so return '0' */
443 if (retval == 0)
444 return 0;
445
446 /*
447 * We have to define 'header' as a pointer to a larger buffer,
448 * because in case of UDP we have to read all the message within a single call
449 */
450 header = (struct rpcap_header *) p->buffer;
451 net_pkt_header = (struct rpcap_pkthdr *) ((char *)p->buffer + sizeof(struct rpcap_header));
452 net_pkt_data = (u_char *)p->buffer + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr);
453
454 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
455 {
456 /* Read the entire message from the network */
457 msglen = sock_recv_dgram(pr->rmt_sockdata, pr->data_ssl, p->buffer,
458 p->bufsize, p->errbuf, PCAP_ERRBUF_SIZE);
459 if (msglen == -1)
460 {
461 /* Network error. */
462 return -1;
463 }
464 if (msglen == -3)
465 {
466 /* Interrupted receive. */
467 return 0;
468 }
469 if ((size_t)msglen < sizeof(struct rpcap_header))
470 {
471 /*
472 * Message is shorter than an rpcap header.
473 */
474 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
475 "UDP packet message is shorter than an rpcap header");
476 return -1;
477 }
478 plen = ntohl(header->plen);
479 if ((size_t)msglen < sizeof(struct rpcap_header) + plen)
480 {
481 /*
482 * Message is shorter than the header claims it
483 * is.
484 */
485 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
486 "UDP packet message is shorter than its rpcap header claims");
487 return -1;
488 }
489 }
490 else
491 {
492 int status;
493
494 if ((size_t)p->cc < sizeof(struct rpcap_header))
495 {
496 /*
497 * We haven't read any of the packet header yet.
498 * The size we should get is the size of the
499 * packet header.
500 */
501 status = rpcap_read_packet_msg(pr, p, sizeof(struct rpcap_header));
502 if (status == -1)
503 {
504 /* Network error. */
505 return -1;
506 }
507 if (status == -3)
508 {
509 /* Interrupted receive. */
510 return 0;
511 }
512 }
513
514 /*
515 * We have the header, so we know how long the
516 * message payload is. The size we should get
517 * is the size of the packet header plus the
518 * size of the payload.
519 */
520 plen = ntohl(header->plen);
521 if (plen > p->bufsize - sizeof(struct rpcap_header))
522 {
523 /*
524 * This is bigger than the largest
525 * record we'd expect. (We do it by
526 * subtracting in order to avoid an
527 * overflow.)
528 */
529 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
530 "Server sent us a message larger than the largest expected packet message");
531 return -1;
532 }
533 status = rpcap_read_packet_msg(pr, p, sizeof(struct rpcap_header) + plen);
534 if (status == -1)
535 {
536 /* Network error. */
537 return -1;
538 }
539 if (status == -3)
540 {
541 /* Interrupted receive. */
542 return 0;
543 }
544
545 /*
546 * We have the entire message; reset the buffer pointer
547 * and count, as the next read should start a new
548 * message.
549 */
550 p->bp = p->buffer;
551 p->cc = 0;
552 }
553
554 /*
555 * We have the entire message.
556 */
557 header->plen = plen;
558
559 /*
560 * Did the server specify the version we negotiated?
561 */
562 if (rpcap_check_msg_ver(pr->rmt_sockdata, pr->data_ssl, pr->protocol_version,
563 header, p->errbuf) == -1)
564 {
565 return 0; /* Return 'no packets received' */
566 }
567
568 /*
569 * Is this a RPCAP_MSG_PACKET message?
570 */
571 if (header->type != RPCAP_MSG_PACKET)
572 {
573 return 0; /* Return 'no packets received' */
574 }
575
576 if (ntohl(net_pkt_header->caplen) > plen)
577 {
578 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
579 "Packet's captured data goes past the end of the received packet message.");
580 return -1;
581 }
582
583 /* Fill in packet header */
584 pkt_header->caplen = ntohl(net_pkt_header->caplen);
585 pkt_header->len = ntohl(net_pkt_header->len);
586 pkt_header->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
587 pkt_header->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
588
589 /* Supply a pointer to the beginning of the packet data */
590 *pkt_data = net_pkt_data;
591
592 /*
593 * I don't update the counter of the packets dropped by the network since we're using TCP,
594 * therefore no packets are dropped. Just update the number of packets received correctly
595 */
596 pr->TotCapt++;
597
598 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
599 {
600 unsigned int npkt;
601
602 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
603 npkt = ntohl(net_pkt_header->npkt);
604
605 if (pr->TotCapt != npkt)
606 {
607 pr->TotNetDrops += (npkt - pr->TotCapt);
608 pr->TotCapt = npkt;
609 }
610 }
611
612 /* Packet read successfully */
613 return 1;
614 }
615
616 /*
617 * This function reads a packet from the network socket.
618 *
619 * This function relies on the pcap_read_nocb_remote to deliver packets. The
620 * difference, here, is that as soon as a packet is read, it is delivered
621 * to the application by means of a callback function.
622 */
623 static int pcap_read_rpcap(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
624 {
625 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
626 struct pcap_pkthdr pkt_header;
627 u_char *pkt_data;
628 int n = 0;
629 int ret;
630
631 /*
632 * If this is client-side, and we haven't already started
633 * the capture, start it now.
634 */
635 if (pr->rmt_clientside)
636 {
637 /* We are on an remote capture */
638 if (!pr->rmt_capstarted)
639 {
640 /*
641 * The capture isn't started yet, so try to
642 * start it.
643 */
644 if (pcap_startcapture_remote(p))
645 return -1;
646 }
647 }
648
649 /*
650 * This can conceivably process more than INT_MAX packets,
651 * which would overflow the packet count, causing it either
652 * to look like a negative number, and thus cause us to
653 * return a value that looks like an error, or overflow
654 * back into positive territory, and thus cause us to
655 * return a too-low count.
656 *
657 * Therefore, if the packet count is unlimited, we clip
658 * it at INT_MAX; this routine is not expected to
659 * process packets indefinitely, so that's not an issue.
660 */
661 if (PACKET_COUNT_IS_UNLIMITED(cnt))
662 cnt = INT_MAX;
663
664 while (n < cnt || PACKET_COUNT_IS_UNLIMITED(cnt))
665 {
666 /*
667 * Has "pcap_breakloop()" been called?
668 */
669 if (p->break_loop) {
670 /*
671 * Yes - clear the flag that indicates that it
672 * has, and return PCAP_ERROR_BREAK to indicate
673 * that we were told to break out of the loop.
674 */
675 p->break_loop = 0;
676 return (PCAP_ERROR_BREAK);
677 }
678
679 /*
680 * Read some packets.
681 */
682 ret = pcap_read_nocb_remote(p, &pkt_header, &pkt_data);
683 if (ret == 1)
684 {
685 /*
686 * We got a packet. Hand it to the callback
687 * and count it so we can return the count.
688 */
689 (*callback)(user, &pkt_header, pkt_data);
690 n++;
691 }
692 else if (ret == -1)
693 {
694 /* Error. */
695 return ret;
696 }
697 else
698 {
699 /*
700 * No packet; this could mean that we timed
701 * out, or that we got interrupted, or that
702 * we got a bad packet.
703 *
704 * Were we told to break out of the loop?
705 */
706 if (p->break_loop) {
707 /*
708 * Yes.
709 */
710 p->break_loop = 0;
711 return (PCAP_ERROR_BREAK);
712 }
713 /* No - return the number of packets we've processed. */
714 return n;
715 }
716 }
717 return n;
718 }
719
720 /*
721 * This function sends a CLOSE command to the capture server if we're in
722 * passive mode and an ENDCAP command to the capture server if we're in
723 * active mode.
724 *
725 * It is called when the user calls pcap_close(). It sends a command
726 * to our peer that says 'ok, let's stop capturing'.
727 *
728 * WARNING: Since we're closing the connection, we do not check for errors.
729 */
730 static void pcap_cleanup_rpcap(pcap_t *fp)
731 {
732 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
733 struct rpcap_header header; /* header of the RPCAP packet */
734 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
735 int active = 0; /* active mode or not? */
736
737 /* detect if we're in active mode */
738 temp = activeHosts;
739 while (temp)
740 {
741 if (temp->sockctrl == pr->rmt_sockctrl)
742 {
743 active = 1;
744 break;
745 }
746 temp = temp->next;
747 }
748
749 if (!active)
750 {
751 rpcap_createhdr(&header, pr->protocol_version,
752 RPCAP_MSG_CLOSE, 0, 0);
753
754 /*
755 * Send the close request; don't report any errors, as
756 * we're closing this pcap_t, and have no place to report
757 * the error. No reply is sent to this message.
758 */
759 (void)sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, (char *)&header,
760 sizeof(struct rpcap_header), NULL, 0);
761 }
762 else
763 {
764 rpcap_createhdr(&header, pr->protocol_version,
765 RPCAP_MSG_ENDCAP_REQ, 0, 0);
766
767 /*
768 * Send the end capture request; don't report any errors,
769 * as we're closing this pcap_t, and have no place to
770 * report the error.
771 */
772 if (sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, (char *)&header,
773 sizeof(struct rpcap_header), NULL, 0) == 0)
774 {
775 /*
776 * Wait for the answer; don't report any errors,
777 * as we're closing this pcap_t, and have no
778 * place to report the error.
779 */
780 if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->ctrl_ssl,
781 pr->protocol_version, RPCAP_MSG_ENDCAP_REQ,
782 &header, NULL) == 0)
783 {
784 (void)rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl,
785 header.plen, NULL);
786 }
787 }
788 }
789
790 if (pr->rmt_sockdata)
791 {
792 #ifdef HAVE_OPENSSL
793 if (pr->data_ssl)
794 {
795 // Finish using the SSL handle for the data socket.
796 // This must be done *before* the socket is closed.
797 ssl_finish(pr->data_ssl);
798 pr->data_ssl = NULL;
799 }
800 #endif
801 sock_close(pr->rmt_sockdata, NULL, 0);
802 pr->rmt_sockdata = 0;
803 }
804
805 if ((!active) && (pr->rmt_sockctrl))
806 {
807 #ifdef HAVE_OPENSSL
808 if (pr->ctrl_ssl)
809 {
810 // Finish using the SSL handle for the control socket.
811 // This must be done *before* the socket is closed.
812 ssl_finish(pr->ctrl_ssl);
813 pr->ctrl_ssl = NULL;
814 }
815 #endif
816 sock_close(pr->rmt_sockctrl, NULL, 0);
817 }
818
819 pr->rmt_sockctrl = 0;
820 pr->ctrl_ssl = NULL;
821
822 if (pr->currentfilter)
823 {
824 free(pr->currentfilter);
825 pr->currentfilter = NULL;
826 }
827
828 pcap_cleanup_live_common(fp);
829
830 /* To avoid inconsistencies in the number of sock_init() */
831 sock_cleanup();
832 }
833
834 /*
835 * This function retrieves network statistics from our peer;
836 * it provides only the standard statistics.
837 */
838 static int pcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps)
839 {
840 struct pcap_stat *retval;
841
842 retval = rpcap_stats_rpcap(p, ps, PCAP_STATS_STANDARD);
843
844 if (retval)
845 return 0;
846 else
847 return -1;
848 }
849
850 #ifdef _WIN32
851 /*
852 * This function retrieves network statistics from our peer;
853 * it provides the additional statistics supported by pcap_stats_ex().
854 */
855 static struct pcap_stat *pcap_stats_ex_rpcap(pcap_t *p, int *pcap_stat_size)
856 {
857 *pcap_stat_size = sizeof (p->stat);
858
859 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
860 return (rpcap_stats_rpcap(p, &(p->stat), PCAP_STATS_EX));
861 }
862 #endif
863
864 /*
865 * This function retrieves network statistics from our peer. It
866 * is used by the two previous functions.
867 *
868 * It can be called in two modes:
869 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
870 * for pcap_stats())
871 * - PCAP_STATS_EX: if we want extended statistics (i.e., for
872 * pcap_stats_ex())
873 *
874 * This 'mode' parameter is needed because in pcap_stats() the variable that
875 * keeps the statistics is allocated by the user. On Windows, this structure
876 * has been extended in order to keep new stats. However, if the user has a
877 * smaller structure and it passes it to pcap_stats(), this function will
878 * try to fill in more data than the size of the structure, so that memory
879 * after the structure will be overwritten.
880 *
881 * So, we need to know it we have to copy just the standard fields, or the
882 * extended fields as well.
883 *
884 * In case we want to copy the extended fields as well, the problem of
885 * memory overflow no longer exists because the structure that's filled
886 * in is part of the pcap_t, so that it can be guaranteed to be large
887 * enough for the additional statistics.
888 *
889 * \param p: the pcap_t structure related to the current instance.
890 *
891 * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
892 * with pcap_stat(), where the structure is allocated by the user. In case
893 * of pcap_stats_ex(), this structure and the function return value point
894 * to the same variable.
895 *
896 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
897 *
898 * \return The structure that keeps the statistics, or NULL in case of error.
899 * The error string is placed in the pcap_t structure.
900 */
901 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode)
902 {
903 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
904 struct rpcap_header header; /* header of the RPCAP packet */
905 struct rpcap_stats netstats; /* statistics sent on the network */
906 uint32 plen; /* data remaining in the message */
907
908 #ifdef _WIN32
909 if (mode != PCAP_STATS_STANDARD && mode != PCAP_STATS_EX)
910 #else
911 if (mode != PCAP_STATS_STANDARD)
912 #endif
913 {
914 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
915 "Invalid stats mode %d", mode);
916 return NULL;
917 }
918
919 /*
920 * If the capture has not yet started, we cannot request statistics
921 * for the capture from our peer, so we return 0 for all statistics,
922 * as nothing's been seen yet.
923 */
924 if (!pr->rmt_capstarted)
925 {
926 ps->ps_drop = 0;
927 ps->ps_ifdrop = 0;
928 ps->ps_recv = 0;
929 #ifdef _WIN32
930 if (mode == PCAP_STATS_EX)
931 {
932 ps->ps_capt = 0;
933 ps->ps_sent = 0;
934 ps->ps_netdrop = 0;
935 }
936 #endif /* _WIN32 */
937
938 return ps;
939 }
940
941 rpcap_createhdr(&header, pr->protocol_version,
942 RPCAP_MSG_STATS_REQ, 0, 0);
943
944 /* Send the PCAP_STATS command */
945 if (sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, (char *)&header,
946 sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE) < 0)
947 return NULL; /* Unrecoverable network error */
948
949 /* Receive and process the reply message header. */
950 if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->ctrl_ssl, pr->protocol_version,
951 RPCAP_MSG_STATS_REQ, &header, p->errbuf) == -1)
952 return NULL; /* Error */
953
954 plen = header.plen;
955
956 /* Read the reply body */
957 if (rpcap_recv(pr->rmt_sockctrl, pr->ctrl_ssl, (char *)&netstats,
958 sizeof(struct rpcap_stats), &plen, p->errbuf) == -1)
959 goto error;
960
961 ps->ps_drop = ntohl(netstats.krnldrop);
962 ps->ps_ifdrop = ntohl(netstats.ifdrop);
963 ps->ps_recv = ntohl(netstats.ifrecv);
964 #ifdef _WIN32
965 if (mode == PCAP_STATS_EX)
966 {
967 ps->ps_capt = pr->TotCapt;
968 ps->ps_netdrop = pr->TotNetDrops;
969 ps->ps_sent = ntohl(netstats.svrcapt);
970 }
971 #endif /* _WIN32 */
972
973 /* Discard the rest of the message. */
974 if (rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, plen, p->errbuf) == -1)
975 goto error_nodiscard;
976
977 return ps;
978
979 error:
980 /*
981 * Discard the rest of the message.
982 * We already reported an error; if this gets an error, just
983 * drive on.
984 */
985 (void)rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, plen, NULL);
986
987 error_nodiscard:
988 return NULL;
989 }
990
991 /*
992 * This function returns the entry in the list of active hosts for this
993 * active connection (active mode only), or NULL if there is no
994 * active connection or an error occurred. It is just for internal
995 * use.
996 *
997 * \param host: a string that keeps the host name of the host for which we
998 * want to get the socket ID for that active connection.
999 *
1000 * \param error: a pointer to an int that is set to 1 if an error occurred
1001 * and 0 otherwise.
1002 *
1003 * \param errbuf: a pointer to a user-allocated buffer (of size
1004 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
1005 * there is one).
1006 *
1007 * \return the entry for this host in the list of active connections
1008 * if found, NULL if it's not found or there's an error.
1009 */
1010 static struct activehosts *
1011 rpcap_remoteact_getsock(const char *host, int *error, char *errbuf)
1012 {
1013 struct activehosts *temp; /* temp var needed to scan the host list chain */
1014 struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
1015 int retval;
1016
1017 /* retrieve the network address corresponding to 'host' */
1018 addrinfo = NULL;
1019 memset(&hints, 0, sizeof(struct addrinfo));
1020 hints.ai_family = PF_UNSPEC;
1021 hints.ai_socktype = SOCK_STREAM;
1022
1023 retval = sock_initaddress(host, "0", &hints, &addrinfo, errbuf,
1024 PCAP_ERRBUF_SIZE);
1025 if (retval != 0)
1026 {
1027 *error = 1;
1028 return NULL;
1029 }
1030
1031 temp = activeHosts;
1032
1033 while (temp)
1034 {
1035 ai_next = addrinfo;
1036 while (ai_next)
1037 {
1038 if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
1039 {
1040 *error = 0;
1041 freeaddrinfo(addrinfo);
1042 return temp;
1043 }
1044
1045 ai_next = ai_next->ai_next;
1046 }
1047 temp = temp->next;
1048 }
1049
1050 if (addrinfo)
1051 freeaddrinfo(addrinfo);
1052
1053 /*
1054 * The host for which you want to get the socket ID does not have an
1055 * active connection.
1056 */
1057 *error = 0;
1058 return NULL;
1059 }
1060
1061 /*
1062 * This function starts a remote capture.
1063 *
1064 * This function is required since the RPCAP protocol decouples the 'open'
1065 * from the 'start capture' functions.
1066 * This function takes all the parameters needed (which have been stored
1067 * into the pcap_t structure) and sends them to the server.
1068 *
1069 * \param fp: the pcap_t descriptor of the device currently open.
1070 *
1071 * \return '0' if everything is fine, '-1' otherwise. The error message
1072 * (if one) is returned into the 'errbuf' field of the pcap_t structure.
1073 */
1074 static int pcap_startcapture_remote(pcap_t *fp)
1075 {
1076 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1077 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1078 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1079 uint16 portdata = 0; /* temp variable needed to keep the network port for the data connection */
1080 uint32 plen;
1081 int active = 0; /* '1' if we're in active mode */
1082 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
1083 char host[INET6_ADDRSTRLEN + 1]; /* numeric name of the other host */
1084
1085 /* socket-related variables*/
1086 struct addrinfo hints; /* temp, needed to open a socket connection */
1087 struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
1088 SOCKET sockdata = 0; /* socket descriptor of the data connection */
1089 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
1090 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
1091 int ai_family; /* temp, keeps the address family used by the control connection */
1092 struct sockaddr_in *sin4;
1093 struct sockaddr_in6 *sin6;
1094
1095 /* RPCAP-related variables*/
1096 struct rpcap_header header; /* header of the RPCAP packet */
1097 struct rpcap_startcapreq *startcapreq; /* start capture request message */
1098 struct rpcap_startcapreply startcapreply; /* start capture reply message */
1099
1100 /* Variables related to the buffer setting */
1101 int res;
1102 socklen_t itemp;
1103 int sockbufsize = 0;
1104 uint32 server_sockbufsize;
1105
1106 // Take the opportunity to clear pr->data_ssl before any goto error,
1107 // as it seems pr->priv is not zeroed after its malloced.
1108 pr->data_ssl = NULL;
1109
1110 /*
1111 * Let's check if sampling has been required.
1112 * If so, let's set it first
1113 */
1114 if (pcap_setsampling_remote(fp) != 0)
1115 return -1;
1116
1117 /* detect if we're in active mode */
1118 temp = activeHosts;
1119 while (temp)
1120 {
1121 if (temp->sockctrl == pr->rmt_sockctrl)
1122 {
1123 active = 1;
1124 break;
1125 }
1126 temp = temp->next;
1127 }
1128
1129 addrinfo = NULL;
1130
1131 /*
1132 * Gets the complete sockaddr structure used in the ctrl connection
1133 * This is needed to get the address family of the control socket
1134 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
1135 * since the ctrl socket can already be open in case of active mode;
1136 * so I would have to call getpeername() anyway
1137 */
1138 saddrlen = sizeof(struct sockaddr_storage);
1139 if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1140 {
1141 sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1142 goto error_nodiscard;
1143 }
1144 ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
1145
1146 /* Get the numeric address of the remote host we are connected to */
1147 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
1148 sizeof(host), NULL, 0, NI_NUMERICHOST))
1149 {
1150 sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1151 goto error_nodiscard;
1152 }
1153
1154 /*
1155 * Data connection is opened by the server toward the client if:
1156 * - we're using TCP, and the user wants us to be in active mode
1157 * - we're using UDP
1158 */
1159 if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1160 {
1161 /*
1162 * We have to create a new socket to receive packets
1163 * We have to do that immediately, since we have to tell the other
1164 * end which network port we picked up
1165 */
1166 memset(&hints, 0, sizeof(struct addrinfo));
1167 /* TEMP addrinfo is NULL in case of active */
1168 hints.ai_family = ai_family; /* Use the same address family of the control socket */
1169 hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1170 hints.ai_flags = AI_PASSIVE; /* Data connection is opened by the server toward the client */
1171
1172 /* Let's the server pick up a free network port for us */
1173 if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1174 goto error_nodiscard;
1175
1176 if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
1177 1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1178 goto error_nodiscard;
1179
1180 /* addrinfo is no longer used */
1181 freeaddrinfo(addrinfo);
1182 addrinfo = NULL;
1183
1184 /* get the complete sockaddr structure used in the data connection */
1185 saddrlen = sizeof(struct sockaddr_storage);
1186 if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1187 {
1188 sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1189 goto error_nodiscard;
1190 }
1191
1192 switch (saddr.ss_family) {
1193
1194 case AF_INET:
1195 sin4 = (struct sockaddr_in *)&saddr;
1196 portdata = sin4->sin_port;
1197 break;
1198
1199 case AF_INET6:
1200 sin6 = (struct sockaddr_in6 *)&saddr;
1201 portdata = sin6->sin6_port;
1202 break;
1203
1204 default:
1205 snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1206 "Local address has unknown address family %u",
1207 saddr.ss_family);
1208 goto error_nodiscard;
1209 }
1210 }
1211
1212 /*
1213 * Now it's time to start playing with the RPCAP protocol
1214 * RPCAP start capture command: create the request message
1215 */
1216 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1217 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1218 goto error_nodiscard;
1219
1220 rpcap_createhdr((struct rpcap_header *) sendbuf,
1221 pr->protocol_version, RPCAP_MSG_STARTCAP_REQ, 0,
1222 sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
1223
1224 /* Fill the structure needed to open an adapter remotely */
1225 startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
1226
1227 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
1228 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1229 goto error_nodiscard;
1230
1231 memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
1232
1233 /* By default, apply half the timeout on one side, half of the other */
1234 fp->opt.timeout = fp->opt.timeout / 2;
1235 startcapreq->read_timeout = htonl(fp->opt.timeout);
1236
1237 /* portdata on the openreq is meaningful only if we're in active mode */
1238 if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1239 {
1240 startcapreq->portdata = portdata;
1241 }
1242
1243 startcapreq->snaplen = htonl(fp->snapshot);
1244 startcapreq->flags = 0;
1245
1246 if (pr->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
1247 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
1248 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
1249 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
1250 if (active)
1251 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
1252
1253 startcapreq->flags = htons(startcapreq->flags);
1254
1255 /* Pack the capture filter */
1256 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
1257 goto error_nodiscard;
1258
1259 if (sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, sendbuf, sendbufidx, fp->errbuf,
1260 PCAP_ERRBUF_SIZE) < 0)
1261 goto error_nodiscard;
1262
1263 /* Receive and process the reply message header. */
1264 if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->ctrl_ssl, pr->protocol_version,
1265 RPCAP_MSG_STARTCAP_REQ, &header, fp->errbuf) == -1)
1266 goto error_nodiscard;
1267
1268 plen = header.plen;
1269
1270 if (rpcap_recv(pr->rmt_sockctrl, pr->ctrl_ssl, (char *)&startcapreply,
1271 sizeof(struct rpcap_startcapreply), &plen, fp->errbuf) == -1)
1272 goto error;
1273
1274 /*
1275 * In case of UDP data stream, the connection is always opened by the daemon
1276 * So, this case is already covered by the code above.
1277 * Now, we have still to handle TCP connections, because:
1278 * - if we're in active mode, we have to wait for a remote connection
1279 * - if we're in passive more, we have to start a connection
1280 *
1281 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1282 * to tell the port we're using to the remote side; in case we're accepting a TCP
1283 * connection, we have to wait this info from the remote side.
1284 */
1285 if (!(pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1286 {
1287 if (!active)
1288 {
1289 char portstring[PCAP_BUF_SIZE];
1290
1291 memset(&hints, 0, sizeof(struct addrinfo));
1292 hints.ai_family = ai_family; /* Use the same address family of the control socket */
1293 hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1294 snprintf(portstring, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
1295
1296 /* Let's the server pick up a free network port for us */
1297 if (sock_initaddress(host, portstring, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1298 goto error;
1299
1300 if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1301 goto error;
1302
1303 /* addrinfo is no longer used */
1304 freeaddrinfo(addrinfo);
1305 addrinfo = NULL;
1306 }
1307 else
1308 {
1309 SOCKET socktemp; /* We need another socket, since we're going to accept() a connection */
1310
1311 /* Connection creation */
1312 saddrlen = sizeof(struct sockaddr_storage);
1313
1314 socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1315
1316 if (socktemp == INVALID_SOCKET)
1317 {
1318 sock_geterror("accept()", fp->errbuf, PCAP_ERRBUF_SIZE);
1319 goto error;
1320 }
1321
1322 /* Now that I accepted the connection, the server socket is no longer needed */
1323 sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1324 sockdata = socktemp;
1325 }
1326 }
1327
1328 /* Let's save the socket of the data connection */
1329 pr->rmt_sockdata = sockdata;
1330
1331 #ifdef HAVE_OPENSSL
1332 if (pr->uses_ssl)
1333 {
1334 pr->data_ssl = ssl_promotion(0, sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1335 if (! pr->data_ssl) goto error;
1336 }
1337 #endif
1338
1339 /*
1340 * Set the size of the socket buffer for the data socket.
1341 * It has the same size as the local capture buffer used
1342 * on the other side of the connection.
1343 */
1344 server_sockbufsize = ntohl(startcapreply.bufsize);
1345
1346 /* Let's get the actual size of the socket buffer */
1347 itemp = sizeof(sockbufsize);
1348
1349 res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
1350 if (res == -1)
1351 {
1352 sock_geterror("pcap_startcapture_remote(): getsockopt() failed", fp->errbuf, PCAP_ERRBUF_SIZE);
1353 goto error;
1354 }
1355
1356 /*
1357 * Warning: on some kernels (e.g. Linux), the size of the user
1358 * buffer does not take into account the pcap_header and such,
1359 * and it is set equal to the snaplen.
1360 *
1361 * In my view, this is wrong (the meaning of the bufsize became
1362 * a bit strange). So, here bufsize is the whole size of the
1363 * user buffer. In case the bufsize returned is too small,
1364 * let's adjust it accordingly.
1365 */
1366 if (server_sockbufsize <= (u_int) fp->snapshot)
1367 server_sockbufsize += sizeof(struct pcap_pkthdr);
1368
1369 /* if the current socket buffer is smaller than the desired one */
1370 if ((u_int) sockbufsize < server_sockbufsize)
1371 {
1372 /*
1373 * Loop until the buffer size is OK or the original
1374 * socket buffer size is larger than this one.
1375 */
1376 for (;;)
1377 {
1378 res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF,
1379 (char *)&(server_sockbufsize),
1380 sizeof(server_sockbufsize));
1381
1382 if (res == 0)
1383 break;
1384
1385 /*
1386 * If something goes wrong, halve the buffer size
1387 * (checking that it does not become smaller than
1388 * the current one).
1389 */
1390 server_sockbufsize /= 2;
1391
1392 if ((u_int) sockbufsize >= server_sockbufsize)
1393 {
1394 server_sockbufsize = sockbufsize;
1395 break;
1396 }
1397 }
1398 }
1399
1400 /*
1401 * Let's allocate the packet; this is required in order to put
1402 * the packet somewhere when extracting data from the socket.
1403 * Since buffering has already been done in the socket buffer,
1404 * here we need just a buffer whose size is equal to the
1405 * largest possible packet message for the snapshot size,
1406 * namely the length of the message header plus the length
1407 * of the packet header plus the snapshot length.
1408 */
1409 fp->bufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + fp->snapshot;
1410
1411 fp->buffer = (u_char *)malloc(fp->bufsize);
1412 if (fp->buffer == NULL)
1413 {
1414 pcap_fmt_errmsg_for_errno(fp->errbuf, PCAP_ERRBUF_SIZE,
1415 errno, "malloc");
1416 goto error;
1417 }
1418
1419 /*
1420 * The buffer is currently empty.
1421 */
1422 fp->bp = fp->buffer;
1423 fp->cc = 0;
1424
1425 /* Discard the rest of the message. */
1426 if (rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, plen, fp->errbuf) == -1)
1427 goto error_nodiscard;
1428
1429 /*
1430 * In case the user does not want to capture RPCAP packets, let's update the filter
1431 * We have to update it here (instead of sending it into the 'StartCapture' message
1432 * because when we generate the 'start capture' we do not know (yet) all the ports
1433 * we're currently using.
1434 */
1435 if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1436 {
1437 struct bpf_program fcode;
1438
1439 if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
1440 goto error;
1441
1442 /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1443 /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1444 if (pcap_updatefilter_remote(fp, &fcode) == -1)
1445 goto error;
1446
1447 pcap_freecode(&fcode);
1448 }
1449
1450 pr->rmt_capstarted = 1;
1451 return 0;
1452
1453 error:
1454 /*
1455 * When the connection has been established, we have to close it. So, at the
1456 * beginning of this function, if an error occur we return immediately with
1457 * a return NULL; when the connection is established, we have to come here
1458 * ('goto error;') in order to close everything properly.
1459 */
1460
1461 /*
1462 * Discard the rest of the message.
1463 * We already reported an error; if this gets an error, just
1464 * drive on.
1465 */
1466 (void)rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, plen, NULL);
1467
1468 error_nodiscard:
1469 #ifdef HAVE_OPENSSL
1470 if (pr->data_ssl)
1471 {
1472 // Finish using the SSL handle for the data socket.
1473 // This must be done *before* the socket is closed.
1474 ssl_finish(pr->data_ssl);
1475 pr->data_ssl = NULL;
1476 }
1477 #endif
1478
1479 /* we can be here because sockdata said 'error' */
1480 if ((sockdata != 0) && (sockdata != INVALID_SOCKET))
1481 sock_close(sockdata, NULL, 0);
1482
1483 if (!active)
1484 {
1485 #ifdef HAVE_OPENSSL
1486 if (pr->ctrl_ssl)
1487 {
1488 // Finish using the SSL handle for the control socket.
1489 // This must be done *before* the socket is closed.
1490 ssl_finish(pr->ctrl_ssl);
1491 pr->ctrl_ssl = NULL;
1492 }
1493 #endif
1494 sock_close(pr->rmt_sockctrl, NULL, 0);
1495 }
1496
1497 if (addrinfo != NULL)
1498 freeaddrinfo(addrinfo);
1499
1500 /*
1501 * We do not have to call pcap_close() here, because this function is always called
1502 * by the user in case something bad happens
1503 */
1504 #if 0
1505 if (fp)
1506 {
1507 pcap_close(fp);
1508 fp= NULL;
1509 }
1510 #endif
1511
1512 return -1;
1513 }
1514
1515 /*
1516 * This function takes a bpf program and sends it to the other host.
1517 *
1518 * This function can be called in two cases:
1519 * - pcap_startcapture_remote() is called (we have to send the filter
1520 * along with the 'start capture' command)
1521 * - we want to update the filter during a capture (i.e. pcap_setfilter()
1522 * after the capture has been started)
1523 *
1524 * This function serializes the filter into the sending buffer ('sendbuf',
1525 * passed as a parameter) and return back. It does not send anything on
1526 * the network.
1527 *
1528 * \param fp: the pcap_t descriptor of the device currently opened.
1529 *
1530 * \param sendbuf: the buffer on which the serialized data has to copied.
1531 *
1532 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1533 *
1534 * \param prog: the bpf program we have to copy.
1535 *
1536 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1537 * is returned into the 'errbuf' field of the pcap_t structure.
1538 */
1539 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
1540 {
1541 struct rpcap_filter *filter;
1542 struct rpcap_filterbpf_insn *insn;
1543 struct bpf_insn *bf_insn;
1544 struct bpf_program fake_prog; /* To be used just in case the user forgot to set a filter */
1545 unsigned int i;
1546
1547 if (prog->bf_len == 0) /* No filters have been specified; so, let's apply a "fake" filter */
1548 {
1549 if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
1550 return -1;
1551
1552 prog = &fake_prog;
1553 }
1554
1555 filter = (struct rpcap_filter *) sendbuf;
1556
1557 if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
1558 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1559 return -1;
1560
1561 filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
1562 filter->nitems = htonl((int32)prog->bf_len);
1563
1564 if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
1565 NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1566 return -1;
1567
1568 insn = (struct rpcap_filterbpf_insn *) (filter + 1);
1569 bf_insn = prog->bf_insns;
1570
1571 for (i = 0; i < prog->bf_len; i++)
1572 {
1573 insn->code = htons(bf_insn->code);
1574 insn->jf = bf_insn->jf;
1575 insn->jt = bf_insn->jt;
1576 insn->k = htonl(bf_insn->k);
1577
1578 insn++;
1579 bf_insn++;
1580 }
1581
1582 return 0;
1583 }
1584
1585 /*
1586 * This function updates a filter on a remote host.
1587 *
1588 * It is called when the user wants to update a filter.
1589 * In case we're capturing from the network, it sends the filter to our
1590 * peer.
1591 * This function is *not* called automatically when the user calls
1592 * pcap_setfilter().
1593 * There will be two cases:
1594 * - the capture has been started: in this case, pcap_setfilter_rpcap()
1595 * calls pcap_updatefilter_remote()
1596 * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
1597 * stores the filter into the pcap_t structure, and then the filter is
1598 * sent with pcap_startcap().
1599 *
1600 * WARNING This function *does not* clear the packet currently into the
1601 * buffers. Therefore, the user has to expect to receive some packets
1602 * that are related to the previous filter. If you want to discard all
1603 * the packets before applying a new filter, you have to close the
1604 * current capture session and start a new one.
1605 *
1606 * XXX - we really should have pcap_setfilter() always discard packets
1607 * received with the old filter, and have a separate pcap_setfilter_noflush()
1608 * function that doesn't discard any packets.
1609 */
1610 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
1611 {
1612 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1613 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1614 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1615 struct rpcap_header header; /* To keep the reply message */
1616
1617 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1618 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1619 return -1;
1620
1621 rpcap_createhdr((struct rpcap_header *) sendbuf,
1622 pr->protocol_version, RPCAP_MSG_UPDATEFILTER_REQ, 0,
1623 sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
1624
1625 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
1626 return -1;
1627
1628 if (sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, sendbuf, sendbufidx, fp->errbuf,
1629 PCAP_ERRBUF_SIZE) < 0)
1630 return -1;
1631
1632 /* Receive and process the reply message header. */
1633 if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->ctrl_ssl, pr->protocol_version,
1634 RPCAP_MSG_UPDATEFILTER_REQ, &header, fp->errbuf) == -1)
1635 return -1;
1636
1637 /*
1638 * It shouldn't have any contents; discard it if it does.
1639 */
1640 if (rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, header.plen, fp->errbuf) == -1)
1641 return -1;
1642
1643 return 0;
1644 }
1645
1646 static void
1647 pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter)
1648 {
1649 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1650
1651 /*
1652 * Check if:
1653 * - We are on an remote capture
1654 * - we do not want to capture RPCAP traffic
1655 *
1656 * If so, we have to save the current filter, because we have to
1657 * add some piece of stuff later
1658 */
1659 if (pr->rmt_clientside &&
1660 (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP))
1661 {
1662 if (pr->currentfilter)
1663 free(pr->currentfilter);
1664
1665 if (filter == NULL)
1666 filter = "";
1667
1668 pr->currentfilter = strdup(filter);
1669 }
1670 }
1671
1672 /*
1673 * This function sends a filter to a remote host.
1674 *
1675 * This function is called when the user wants to set a filter.
1676 * It sends the filter to our peer.
1677 * This function is called automatically when the user calls pcap_setfilter().
1678 *
1679 * Parameters and return values are exactly the same of pcap_setfilter().
1680 */
1681 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog)
1682 {
1683 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1684
1685 if (!pr->rmt_capstarted)
1686 {
1687 /* copy filter into the pcap_t structure */
1688 if (install_bpf_program(fp, prog) == -1)
1689 return -1;
1690 return 0;
1691 }
1692
1693 /* we have to update a filter during run-time */
1694 if (pcap_updatefilter_remote(fp, prog))
1695 return -1;
1696
1697 return 0;
1698 }
1699
1700 /*
1701 * This function updates the current filter in order not to capture rpcap
1702 * packets.
1703 *
1704 * This function is called *only* when the user wants exclude RPCAP packets
1705 * related to the current session from the captured packets.
1706 *
1707 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1708 * is returned into the 'errbuf' field of the pcap_t structure.
1709 */
1710 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
1711 {
1712 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1713 int RetVal = 0;
1714
1715 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1716 if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1717 {
1718 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
1719 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
1720 char myaddress[128];
1721 char myctrlport[128];
1722 char mydataport[128];
1723 char peeraddress[128];
1724 char peerctrlport[128];
1725 char *newfilter;
1726
1727 /* Get the name/port of our peer */
1728 saddrlen = sizeof(struct sockaddr_storage);
1729 if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1730 {
1731 sock_geterror("getpeername()", fp->errbuf, PCAP_ERRBUF_SIZE);
1732 return -1;
1733 }
1734
1735 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
1736 sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1737 {
1738 sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1739 return -1;
1740 }
1741
1742 /* We cannot check the data port, because this is available only in case of TCP sockets */
1743 /* Get the name/port of the current host */
1744 if (getsockname(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1745 {
1746 sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1747 return -1;
1748 }
1749
1750 /* Get the local port the system picked up */
1751 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
1752 sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1753 {
1754 sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1755 return -1;
1756 }
1757
1758 /* Let's now check the data port */
1759 if (getsockname(pr->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1760 {
1761 sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1762 return -1;
1763 }
1764
1765 /* Get the local port the system picked up */
1766 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
1767 {
1768 sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1769 return -1;
1770 }
1771
1772 if (pr->currentfilter && pr->currentfilter[0] != '\0')
1773 {
1774 /*
1775 * We have a current filter; add items to it to
1776 * filter out this rpcap session.
1777 */
1778 if (pcap_asprintf(&newfilter,
1779 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1780 pr->currentfilter, myaddress, peeraddress,
1781 myctrlport, peerctrlport, myaddress, peeraddress,
1782 mydataport) == -1)
1783 {
1784 /* Failed. */
1785 snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1786 "Can't allocate memory for new filter");
1787 return -1;
1788 }
1789 }
1790 else
1791 {
1792 /*
1793 * We have no current filter; construct a filter to
1794 * filter out this rpcap session.
1795 */
1796 if (pcap_asprintf(&newfilter,
1797 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1798 myaddress, peeraddress, myctrlport, peerctrlport,
1799 myaddress, peeraddress, mydataport) == -1)
1800 {
1801 /* Failed. */
1802 snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1803 "Can't allocate memory for new filter");
1804 return -1;
1805 }
1806 }
1807
1808 /*
1809 * This is only an hack to prevent the save_current_filter
1810 * routine, which will be called when we call pcap_compile(),
1811 * from saving the modified filter.
1812 */
1813 pr->rmt_clientside = 0;
1814
1815 if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
1816 RetVal = -1;
1817
1818 /* Undo the hack. */
1819 pr->rmt_clientside = 1;
1820
1821 free(newfilter);
1822 }
1823
1824 return RetVal;
1825 }
1826
1827 /*
1828 * This function sets sampling parameters in the remote host.
1829 *
1830 * It is called when the user wants to set activate sampling on the
1831 * remote host.
1832 *
1833 * Sampling parameters are defined into the 'pcap_t' structure.
1834 *
1835 * \param p: the pcap_t descriptor of the device currently opened.
1836 *
1837 * \return '0' if everything is OK, '-1' is something goes wrong. The
1838 * error message is returned in the 'errbuf' member of the pcap_t structure.
1839 */
1840 static int pcap_setsampling_remote(pcap_t *fp)
1841 {
1842 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1843 char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1844 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1845 struct rpcap_header header; /* To keep the reply message */
1846 struct rpcap_sampling *sampling_pars; /* Structure that is needed to send sampling parameters to the remote host */
1847
1848 /* If no samping is requested, return 'ok' */
1849 if (fp->rmt_samp.method == PCAP_SAMP_NOSAMP)
1850 return 0;
1851
1852 /*
1853 * Check for sampling parameters that don't fit in a message.
1854 * We'll let the server complain about invalid parameters
1855 * that do fit into the message.
1856 */
1857 if (fp->rmt_samp.method < 0 || fp->rmt_samp.method > 255) {
1858 snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1859 "Invalid sampling method %d", fp->rmt_samp.method);
1860 return -1;
1861 }
1862 if (fp->rmt_samp.value < 0 || fp->rmt_samp.value > 65535) {
1863 snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1864 "Invalid sampling value %d", fp->rmt_samp.value);
1865 return -1;
1866 }
1867
1868 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1869 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1870 return -1;
1871
1872 rpcap_createhdr((struct rpcap_header *) sendbuf,
1873 pr->protocol_version, RPCAP_MSG_SETSAMPLING_REQ, 0,
1874 sizeof(struct rpcap_sampling));
1875
1876 /* Fill the structure needed to open an adapter remotely */
1877 sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
1878
1879 if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
1880 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1881 return -1;
1882
1883 memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
1884
1885 sampling_pars->method = (uint8)fp->rmt_samp.method;
1886 sampling_pars->value = (uint16)htonl(fp->rmt_samp.value);
1887
1888 if (sock_send(pr->rmt_sockctrl, pr->ctrl_ssl, sendbuf, sendbufidx, fp->errbuf,
1889 PCAP_ERRBUF_SIZE) < 0)
1890 return -1;
1891
1892 /* Receive and process the reply message header. */
1893 if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->ctrl_ssl, pr->protocol_version,
1894 RPCAP_MSG_SETSAMPLING_REQ, &header, fp->errbuf) == -1)
1895 return -1;
1896
1897 /*
1898 * It shouldn't have any contents; discard it if it does.
1899 */
1900 if (rpcap_discard(pr->rmt_sockctrl, pr->ctrl_ssl, header.plen, fp->errbuf) == -1)
1901 return -1;
1902
1903 return 0;
1904 }
1905
1906 /*********************************************************
1907 * *
1908 * Miscellaneous functions *
1909 * *
1910 *********************************************************/
1911
1912 /*
1913 * This function performs authentication and protocol version
1914 * negotiation. It is required in order to open the connection
1915 * with the other end party.
1916 *
1917 * It sends authentication parameters on the control socket and
1918 * reads the reply. If the reply is a success indication, it
1919 * checks whether the reply includes minimum and maximum supported
1920 * versions from the server; if not, it assumes both are 0, as
1921 * that means it's an older server that doesn't return supported
1922 * version numbers in authentication replies, so it only supports
1923 * version 0. It then tries to determine the maximum version
1924 * supported both by us and by the server. If it can find such a
1925 * version, it sets us up to use that version; otherwise, it fails,
1926 * indicating that there is no version supported by us and by the
1927 * server.
1928 *
1929 * \param sock: the socket we are currently using.
1930 *
1931 * \param ver: pointer to variable to which to set the protocol version
1932 * number we selected.
1933 *
1934 * \param auth: authentication parameters that have to be sent.
1935 *
1936 * \param errbuf: a pointer to a user-allocated buffer (of size
1937 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1938 * is one). It could be a network problem or the fact that the authorization
1939 * failed.
1940 *
1941 * \return '0' if everything is fine, '-1' for an error. For errors,
1942 * an error message string is returned in the 'errbuf' variable.
1943 */
1944 static int rpcap_doauth(SOCKET sockctrl, SSL *ssl, uint8 *ver, struct pcap_rmtauth *auth, char *errbuf)
1945 {
1946 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data that has to be sent is buffered */
1947 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1948 uint16 length; /* length of the payload of this message */
1949 struct rpcap_auth *rpauth;
1950 uint16 auth_type;
1951 struct rpcap_header header;
1952 size_t str_length;
1953 uint32 plen;
1954 struct rpcap_authreply authreply; /* authentication reply message */
1955 uint8 ourvers;
1956
1957 if (auth)
1958 {
1959 switch (auth->type)
1960 {
1961 case RPCAP_RMTAUTH_NULL:
1962 length = sizeof(struct rpcap_auth);
1963 break;
1964
1965 case RPCAP_RMTAUTH_PWD:
1966 length = sizeof(struct rpcap_auth);
1967 if (auth->username)
1968 {
1969 str_length = strlen(auth->username);
1970 if (str_length > 65535)
1971 {
1972 snprintf(errbuf, PCAP_ERRBUF_SIZE, "User name is too long (> 65535 bytes)");
1973 return -1;
1974 }
1975 length += (uint16)str_length;
1976 }
1977 if (auth->password)
1978 {
1979 str_length = strlen(auth->password);
1980 if (str_length > 65535)
1981 {
1982 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Password is too long (> 65535 bytes)");
1983 return -1;
1984 }
1985 length += (uint16)str_length;
1986 }
1987 break;
1988
1989 default:
1990 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1991 return -1;
1992 }
1993
1994 auth_type = (uint16)auth->type;
1995 }
1996 else
1997 {
1998 auth_type = RPCAP_RMTAUTH_NULL;
1999 length = sizeof(struct rpcap_auth);
2000 }
2001
2002 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2003 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
2004 return -1;
2005
2006 rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
2007 RPCAP_MSG_AUTH_REQ, 0, length);
2008
2009 rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
2010
2011 if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
2012 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
2013 return -1;
2014
2015 memset(rpauth, 0, sizeof(struct rpcap_auth));
2016
2017 rpauth->type = htons(auth_type);
2018
2019 if (auth_type == RPCAP_RMTAUTH_PWD)
2020 {
2021 if (auth->username)
2022 rpauth->slen1 = (uint16)strlen(auth->username);
2023 else
2024 rpauth->slen1 = 0;
2025
2026 if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
2027 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
2028 return -1;
2029
2030 if (auth->password)
2031 rpauth->slen2 = (uint16)strlen(auth->password);
2032 else
2033 rpauth->slen2 = 0;
2034
2035 if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
2036 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
2037 return -1;
2038
2039 rpauth->slen1 = htons(rpauth->slen1);
2040 rpauth->slen2 = htons(rpauth->slen2);
2041 }
2042
2043 if (sock_send(sockctrl, ssl, sendbuf, sendbufidx, errbuf,
2044 PCAP_ERRBUF_SIZE) < 0)
2045 return -1;
2046
2047 /* Receive and process the reply message header */
2048 if (rpcap_process_msg_header(sockctrl, ssl, 0, RPCAP_MSG_AUTH_REQ,
2049 &header, errbuf) == -1)
2050 return -1;
2051
2052 /*
2053 * OK, it's an authentication reply, so we're logged in.
2054 *
2055 * Did it send any additional information?
2056 */
2057 plen = header.plen;
2058 if (plen != 0)
2059 {
2060 /* Yes - is it big enough to be version information? */
2061 if (plen < sizeof(struct rpcap_authreply))
2062 {
2063 /* No - discard it and fail. */
2064 (void)rpcap_discard(sockctrl, ssl, plen, NULL);
2065 return -1;
2066 }
2067
2068 /* Read the reply body */
2069 if (rpcap_recv(sockctrl, ssl, (char *)&authreply,
2070 sizeof(struct rpcap_authreply), &plen, errbuf) == -1)
2071 {
2072 (void)rpcap_discard(sockctrl, ssl, plen, NULL);
2073 return -1;
2074 }
2075
2076 /* Discard the rest of the message, if there is any. */
2077 if (rpcap_discard(sockctrl, ssl, plen, errbuf) == -1)
2078 return -1;
2079
2080 /*
2081 * Check the minimum and maximum versions for sanity;
2082 * the minimum must be <= the maximum.
2083 */
2084 if (authreply.minvers > authreply.maxvers)
2085 {
2086 /*
2087 * Bogus - give up on this server.
2088 */
2089 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2090 "The server's minimum supported protocol version is greater than its maximum supported protocol version");
2091 return -1;
2092 }
2093 }
2094 else
2095 {
2096 /* No - it supports only version 0. */
2097 authreply.minvers = 0;
2098 authreply.maxvers = 0;
2099 }
2100
2101 /*
2102 * OK, let's start with the maximum version the server supports.
2103 */
2104 ourvers = authreply.maxvers;
2105
2106 #if RPCAP_MIN_VERSION != 0
2107 /*
2108 * If that's less than the minimum version we support, we
2109 * can't communicate.
2110 */
2111 if (ourvers < RPCAP_MIN_VERSION)
2112 goto novers;
2113 #endif
2114
2115 /*
2116 * If that's greater than the maximum version we support,
2117 * choose the maximum version we support.
2118 */
2119 if (ourvers > RPCAP_MAX_VERSION)
2120 {
2121 ourvers = RPCAP_MAX_VERSION;
2122
2123 /*
2124 * If that's less than the minimum version they
2125 * support, we can't communicate.
2126 */
2127 if (ourvers < authreply.minvers)
2128 goto novers;
2129 }
2130
2131 *ver = ourvers;
2132 return 0;
2133
2134 novers:
2135 /*
2136 * There is no version we both support; that is a fatal error.
2137 */
2138 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2139 "The server doesn't support any protocol version that we support");
2140 return -1;
2141 }
2142
2143 /* We don't currently support non-blocking mode. */
2144 static int
2145 pcap_getnonblock_rpcap(pcap_t *p)
2146 {
2147 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2148 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2149 return (-1);
2150 }
2151
2152 static int
2153 pcap_setnonblock_rpcap(pcap_t *p, int nonblock _U_)
2154 {
2155 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2156 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2157 return (-1);
2158 }
2159
2160 static int
2161 rpcap_setup_session(const char *source, struct pcap_rmtauth *auth,
2162 int *activep, SOCKET *sockctrlp, uint8 *uses_sslp, SSL **sslp,
2163 int rmt_flags, uint8 *protocol_versionp, char *host, char *port,
2164 char *iface, char *errbuf)
2165 {
2166 int type;
2167 struct activehosts *activeconn; /* active connection, if there is one */
2168 int error; /* 1 if rpcap_remoteact_getsock got an error */
2169
2170 /*
2171 * Determine the type of the source (NULL, file, local, remote).
2172 * You must have a valid source string even if we're in active mode,
2173 * because otherwise the call to the following function will fail.
2174 */
2175 if (pcap_parsesrcstr_ex(source, &type, host, port, iface, uses_sslp,
2176 errbuf) == -1)
2177 return -1;
2178
2179 /*
2180 * It must be remote.
2181 */
2182 if (type != PCAP_SRC_IFREMOTE)
2183 {
2184 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2185 "Non-remote interface passed to remote capture routine");
2186 return -1;
2187 }
2188
2189 /*
2190 * We don't yet support DTLS, so if the user asks for a TLS
2191 * connection and asks for data packets to be sent over UDP,
2192 * we have to give up.
2193 */
2194 if (*uses_sslp && (rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
2195 {
2196 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2197 "TLS not supported with UDP forward of remote packets");
2198 return -1;
2199 }
2200
2201 /* Warning: this call can be the first one called by the user. */
2202 /* For this reason, we have to initialize the Winsock support. */
2203 if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
2204 return -1;
2205
2206 /* Check for active mode */
2207 activeconn = rpcap_remoteact_getsock(host, &error, errbuf);
2208 if (activeconn != NULL)
2209 {
2210 *activep = 1;
2211 *sockctrlp = activeconn->sockctrl;
2212 *sslp = activeconn->ssl;
2213 *protocol_versionp = activeconn->protocol_version;
2214 }
2215 else
2216 {
2217 *activep = 0;
2218 struct addrinfo hints; /* temp variable needed to resolve hostnames into to socket representation */
2219 struct addrinfo *addrinfo; /* temp variable needed to resolve hostnames into to socket representation */
2220
2221 if (error)
2222 {
2223 /*
2224 * Call failed.
2225 */
2226 return -1;
2227 }
2228
2229 /*
2230 * We're not in active mode; let's try to open a new
2231 * control connection.
2232 */
2233 memset(&hints, 0, sizeof(struct addrinfo));
2234 hints.ai_family = PF_UNSPEC;
2235 hints.ai_socktype = SOCK_STREAM;
2236
2237 if (port[0] == 0)
2238 {
2239 /* the user chose not to specify the port */
2240 if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT,
2241 &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2242 return -1;
2243 }
2244 else
2245 {
2246 if (sock_initaddress(host, port, &hints, &addrinfo,
2247 errbuf, PCAP_ERRBUF_SIZE) == -1)
2248 return -1;
2249 }
2250
2251 if ((*sockctrlp = sock_open(addrinfo, SOCKOPEN_CLIENT, 0,
2252 errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
2253 {
2254 freeaddrinfo(addrinfo);
2255 return -1;
2256 }
2257
2258 /* addrinfo is no longer used */
2259 freeaddrinfo(addrinfo);
2260 addrinfo = NULL;
2261
2262 if (*uses_sslp)
2263 {
2264 #ifdef HAVE_OPENSSL
2265 *sslp = ssl_promotion(0, *sockctrlp, errbuf,
2266 PCAP_ERRBUF_SIZE);
2267 if (!*sslp)
2268 {
2269 sock_close(*sockctrlp, NULL, 0);
2270 return -1;
2271 }
2272 #else
2273 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2274 "No TLS support");
2275 sock_close(*sockctrlp, NULL, 0);
2276 return -1;
2277 #endif
2278 }
2279
2280 if (rpcap_doauth(*sockctrlp, *sslp, protocol_versionp, auth,
2281 errbuf) == -1)
2282 {
2283 #ifdef HAVE_OPENSSL
2284 if (*sslp)
2285 {
2286 // Finish using the SSL handle for the socket.
2287 // This must be done *before* the socket is
2288 // closed.
2289 ssl_finish(*sslp);
2290 }
2291 #endif
2292 sock_close(*sockctrlp, NULL, 0);
2293 return -1;
2294 }
2295 }
2296 return 0;
2297 }
2298
2299 /*
2300 * This function opens a remote adapter by opening an RPCAP connection and
2301 * so on.
2302 *
2303 * It does the job of pcap_open_live() for a remote interface; it's called
2304 * by pcap_open() for remote interfaces.
2305 *
2306 * We do not start the capture until pcap_startcapture_remote() is called.
2307 *
2308 * This is because, when doing a remote capture, we cannot start capturing
2309 * data as soon as the 'open adapter' command is sent. Suppose the remote
2310 * adapter is already overloaded; if we start a capture (which, by default,
2311 * has a NULL filter) the new traffic can saturate the network.
2312 *
2313 * Instead, we want to "open" the adapter, then send a "start capture"
2314 * command only when we're ready to start the capture.
2315 * This function does this job: it sends an "open adapter" command
2316 * (according to the RPCAP protocol), but it does not start the capture.
2317 *
2318 * Since the other libpcap functions do not share this way of life, we
2319 * have to do some dirty things in order to make everything work.
2320 *
2321 * \param source: see pcap_open().
2322 * \param snaplen: see pcap_open().
2323 * \param flags: see pcap_open().
2324 * \param read_timeout: see pcap_open().
2325 * \param auth: see pcap_open().
2326 * \param errbuf: see pcap_open().
2327 *
2328 * \return a pcap_t pointer in case of success, NULL otherwise. In case of
2329 * success, the pcap_t pointer can be used as a parameter to the following
2330 * calls (pcap_compile() and so on). In case of problems, errbuf contains
2331 * a text explanation of error.
2332 *
2333 * WARNING: In case we call pcap_compile() and the capture has not yet
2334 * been started, the filter will be saved into the pcap_t structure,
2335 * and it will be sent to the other host later (when
2336 * pcap_startcapture_remote() is called).
2337 */
2338 pcap_t *pcap_open_rpcap(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
2339 {
2340 pcap_t *fp;
2341 char *source_str;
2342 struct pcap_rpcap *pr; /* structure used when doing a remote live capture */
2343 char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
2344 SOCKET sockctrl;
2345 SSL *ssl = NULL;
2346 uint8 protocol_version; /* negotiated protocol version */
2347 int active;
2348 uint32 plen;
2349 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
2350 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
2351
2352 /* RPCAP-related variables */
2353 struct rpcap_header header; /* header of the RPCAP packet */
2354 struct rpcap_openreply openreply; /* open reply message */
2355
2356 fp = PCAP_CREATE_COMMON(errbuf, struct pcap_rpcap);
2357 if (fp == NULL)
2358 {
2359 return NULL;
2360 }
2361 source_str = strdup(source);
2362 if (source_str == NULL) {
2363 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2364 errno, "malloc");
2365 return NULL;
2366 }
2367
2368 /*
2369 * Turn a negative snapshot value (invalid), a snapshot value of
2370 * 0 (unspecified), or a value bigger than the normal maximum
2371 * value, into the maximum allowed value.
2372 *
2373 * If some application really *needs* a bigger snapshot
2374 * length, we should just increase MAXIMUM_SNAPLEN.
2375 *
2376 * XXX - should we leave this up to the remote server to
2377 * do?
2378 */
2379 if (snaplen <= 0 || snaplen > MAXIMUM_SNAPLEN)
2380 snaplen = MAXIMUM_SNAPLEN;
2381
2382 fp->opt.device = source_str;
2383 fp->snapshot = snaplen;
2384 fp->opt.timeout = read_timeout;
2385 pr = fp->priv;
2386 pr->rmt_flags = flags;
2387
2388 /*
2389 * Attempt to set up the session with the server.
2390 */
2391 if (rpcap_setup_session(fp->opt.device, auth, &active, &sockctrl,
2392 &pr->uses_ssl, &ssl, flags, &protocol_version, host, ctrlport,
2393 iface, errbuf) == -1)
2394 {
2395 /* Session setup failed. */
2396 pcap_close(fp);
2397 return NULL;
2398 }
2399
2400 /* All good so far, save the ssl handler */
2401 ssl_main = ssl;
2402
2403 /*
2404 * Now it's time to start playing with the RPCAP protocol
2405 * RPCAP open command: create the request message
2406 */
2407 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2408 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
2409 goto error_nodiscard;
2410
2411 rpcap_createhdr((struct rpcap_header *) sendbuf, protocol_version,
2412 RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
2413
2414 if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
2415 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
2416 goto error_nodiscard;
2417
2418 if (sock_send(sockctrl, ssl, sendbuf, sendbufidx, errbuf,
2419 PCAP_ERRBUF_SIZE) < 0)
2420 goto error_nodiscard;
2421
2422 /* Receive and process the reply message header. */
2423 if (rpcap_process_msg_header(sockctrl, ssl, protocol_version,
2424 RPCAP_MSG_OPEN_REQ, &header, errbuf) == -1)
2425 goto error_nodiscard;
2426 plen = header.plen;
2427
2428 /* Read the reply body */
2429 if (rpcap_recv(sockctrl, ssl, (char *)&openreply,
2430 sizeof(struct rpcap_openreply), &plen, errbuf) == -1)
2431 goto error;
2432
2433 /* Discard the rest of the message, if there is any. */
2434 if (rpcap_discard(sockctrl, ssl, plen, errbuf) == -1)
2435 goto error_nodiscard;
2436
2437 /* Set proper fields into the pcap_t struct */
2438 fp->linktype = ntohl(openreply.linktype);
2439 pr->rmt_sockctrl = sockctrl;
2440 pr->ctrl_ssl = ssl;
2441 pr->protocol_version = protocol_version;
2442 pr->rmt_clientside = 1;
2443
2444 /* This code is duplicated from the end of this function */
2445 fp->read_op = pcap_read_rpcap;
2446 fp->save_current_filter_op = pcap_save_current_filter_rpcap;
2447 fp->setfilter_op = pcap_setfilter_rpcap;
2448 fp->getnonblock_op = pcap_getnonblock_rpcap;
2449 fp->setnonblock_op = pcap_setnonblock_rpcap;
2450 fp->stats_op = pcap_stats_rpcap;
2451 #ifdef _WIN32
2452 fp->stats_ex_op = pcap_stats_ex_rpcap;
2453 #endif
2454 fp->cleanup_op = pcap_cleanup_rpcap;
2455
2456 fp->activated = 1;
2457 return fp;
2458
2459 error:
2460 /*
2461 * When the connection has been established, we have to close it. So, at the
2462 * beginning of this function, if an error occur we return immediately with
2463 * a return NULL; when the connection is established, we have to come here
2464 * ('goto error;') in order to close everything properly.
2465 */
2466
2467 /*
2468 * Discard the rest of the message.
2469 * We already reported an error; if this gets an error, just
2470 * drive on.
2471 */
2472 (void)rpcap_discard(sockctrl, pr->ctrl_ssl, plen, NULL);
2473
2474 error_nodiscard:
2475 if (!active)
2476 {
2477 #ifdef HAVE_OPENSSL
2478 if (ssl)
2479 {
2480 // Finish using the SSL handle for the socket.
2481 // This must be done *before* the socket is closed.
2482 ssl_finish(ssl);
2483 }
2484 #endif
2485 sock_close(sockctrl, NULL, 0);
2486 }
2487
2488 pcap_close(fp);
2489 return NULL;
2490 }
2491
2492 /* String identifier to be used in the pcap_findalldevs_ex() */
2493 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2494 #define PCAP_TEXT_SOURCE_ADAPTER_LEN (sizeof PCAP_TEXT_SOURCE_ADAPTER - 1)
2495 /* String identifier to be used in the pcap_findalldevs_ex() */
2496 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2497 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST_LEN (sizeof PCAP_TEXT_SOURCE_ON_REMOTE_HOST - 1)
2498
2499 static void
2500 freeaddr(struct pcap_addr *addr)
2501 {
2502 free(addr->addr);
2503 free(addr->netmask);
2504 free(addr->broadaddr);
2505 free(addr->dstaddr);
2506 free(addr);
2507 }
2508
2509 int
2510 pcap_findalldevs_ex_remote(const char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
2511 {
2512 uint8 protocol_version; /* protocol version */
2513 SOCKET sockctrl; /* socket descriptor of the control connection */
2514 SSL *ssl = NULL; /* optional SSL handler for sockctrl */
2515 uint32 plen;
2516 struct rpcap_header header; /* structure that keeps the general header of the rpcap protocol */
2517 int i, j; /* temp variables */
2518 int nif; /* Number of interfaces listed */
2519 int active; /* 'true' if we the other end-party is in active mode */
2520 uint8 uses_ssl;
2521 char host[PCAP_BUF_SIZE], port[PCAP_BUF_SIZE];
2522 char tmpstring[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2523 pcap_if_t *lastdev; /* Last device in the pcap_if_t list */
2524 pcap_if_t *dev; /* Device we're adding to the pcap_if_t list */
2525
2526 /* List starts out empty. */
2527 (*alldevs) = NULL;
2528 lastdev = NULL;
2529
2530 /*
2531 * Attempt to set up the session with the server.
2532 */
2533 if (rpcap_setup_session(source, auth, &active, &sockctrl, &uses_ssl,
2534 &ssl, 0, &protocol_version, host, port, NULL, errbuf) == -1)
2535 {
2536 /* Session setup failed. */
2537 return -1;
2538 }
2539
2540 /* RPCAP findalldevs command */
2541 rpcap_createhdr(&header, protocol_version, RPCAP_MSG_FINDALLIF_REQ,
2542 0, 0);
2543
2544 if (sock_send(sockctrl, ssl, (char *)&header, sizeof(struct rpcap_header),
2545 errbuf, PCAP_ERRBUF_SIZE) < 0)
2546 goto error_nodiscard;
2547
2548 /* Receive and process the reply message header. */
2549 if (rpcap_process_msg_header(sockctrl, ssl, protocol_version,
2550 RPCAP_MSG_FINDALLIF_REQ, &header, errbuf) == -1)
2551 goto error_nodiscard;
2552
2553 plen = header.plen;
2554
2555 /* read the number of interfaces */
2556 nif = ntohs(header.value);
2557
2558 /* loop until all interfaces have been received */
2559 for (i = 0; i < nif; i++)
2560 {
2561 struct rpcap_findalldevs_if findalldevs_if;
2562 char tmpstring2[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2563 struct pcap_addr *addr, *prevaddr;
2564
2565 tmpstring2[PCAP_BUF_SIZE] = 0;
2566
2567 /* receive the findalldevs structure from remote host */
2568 if (rpcap_recv(sockctrl, ssl, (char *)&findalldevs_if,
2569 sizeof(struct rpcap_findalldevs_if), &plen, errbuf) == -1)
2570 goto error;
2571
2572 findalldevs_if.namelen = ntohs(findalldevs_if.namelen);
2573 findalldevs_if.desclen = ntohs(findalldevs_if.desclen);
2574 findalldevs_if.naddr = ntohs(findalldevs_if.naddr);
2575
2576 /* allocate the main structure */
2577 dev = (pcap_if_t *)malloc(sizeof(pcap_if_t));
2578 if (dev == NULL)
2579 {
2580 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2581 errno, "malloc() failed");
2582 goto error;
2583 }
2584
2585 /* Initialize the structure to 'zero' */
2586 memset(dev, 0, sizeof(pcap_if_t));
2587
2588 /* Append it to the list. */
2589 if (lastdev == NULL)
2590 {
2591 /*
2592 * List is empty, so it's also the first device.
2593 */
2594 *alldevs = dev;
2595 }
2596 else
2597 {
2598 /*
2599 * Append after the last device.
2600 */
2601 lastdev->next = dev;
2602 }
2603 /* It's now the last device. */
2604 lastdev = dev;
2605
2606 /* allocate mem for name and description */
2607 if (findalldevs_if.namelen)
2608 {
2609
2610 if (findalldevs_if.namelen >= sizeof(tmpstring))
2611 {
2612 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface name too long");
2613 goto error;
2614 }
2615
2616 /* Retrieve adapter name */
2617 if (rpcap_recv(sockctrl, ssl, tmpstring,
2618 findalldevs_if.namelen, &plen, errbuf) == -1)
2619 goto error;
2620
2621 tmpstring[findalldevs_if.namelen] = 0;
2622
2623 /* Create the new device identifier */
2624 if (pcap_createsrcstr_ex(tmpstring2, PCAP_SRC_IFREMOTE,
2625 host, port, tmpstring, uses_ssl, errbuf) == -1)
2626 goto error;
2627
2628 dev->name = strdup(tmpstring2);
2629 if (dev->name == NULL)
2630 {
2631 pcap_fmt_errmsg_for_errno(errbuf,
2632 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2633 goto error;
2634 }
2635 }
2636
2637 if (findalldevs_if.desclen)
2638 {
2639 if (findalldevs_if.desclen >= sizeof(tmpstring))
2640 {
2641 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface description too long");
2642 goto error;
2643 }
2644
2645 /* Retrieve adapter description */
2646 if (rpcap_recv(sockctrl, ssl, tmpstring,
2647 findalldevs_if.desclen, &plen, errbuf) == -1)
2648 goto error;
2649
2650 tmpstring[findalldevs_if.desclen] = 0;
2651
2652 if (pcap_asprintf(&dev->description,
2653 "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER,
2654 tmpstring, PCAP_TEXT_SOURCE_ON_REMOTE_HOST, host) == -1)
2655 {
2656 pcap_fmt_errmsg_for_errno(errbuf,
2657 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2658 goto error;
2659 }
2660 }
2661
2662 dev->flags = ntohl(findalldevs_if.flags);
2663
2664 prevaddr = NULL;
2665 /* loop until all addresses have been received */
2666 for (j = 0; j < findalldevs_if.naddr; j++)
2667 {
2668 struct rpcap_findalldevs_ifaddr ifaddr;
2669
2670 /* Retrieve the interface addresses */
2671 if (rpcap_recv(sockctrl, ssl, (char *)&ifaddr,
2672 sizeof(struct rpcap_findalldevs_ifaddr),
2673 &plen, errbuf) == -1)
2674 goto error;
2675
2676 /*
2677 * Deserialize all the address components.
2678 */
2679 addr = (struct pcap_addr *) malloc(sizeof(struct pcap_addr));
2680 if (addr == NULL)
2681 {
2682 pcap_fmt_errmsg_for_errno(errbuf,
2683 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2684 goto error;
2685 }
2686 addr->next = NULL;
2687 addr->addr = NULL;
2688 addr->netmask = NULL;
2689 addr->broadaddr = NULL;
2690 addr->dstaddr = NULL;
2691
2692 if (rpcap_deseraddr(&ifaddr.addr,
2693 (struct sockaddr_storage **) &addr->addr, errbuf) == -1)
2694 {
2695 freeaddr(addr);
2696 goto error;
2697 }
2698 if (rpcap_deseraddr(&ifaddr.netmask,
2699 (struct sockaddr_storage **) &addr->netmask, errbuf) == -1)
2700 {
2701 freeaddr(addr);
2702 goto error;
2703 }
2704 if (rpcap_deseraddr(&ifaddr.broadaddr,
2705 (struct sockaddr_storage **) &addr->broadaddr, errbuf) == -1)
2706 {
2707 freeaddr(addr);
2708 goto error;
2709 }
2710 if (rpcap_deseraddr(&ifaddr.dstaddr,
2711 (struct sockaddr_storage **) &addr->dstaddr, errbuf) == -1)
2712 {
2713 freeaddr(addr);
2714 goto error;
2715 }
2716
2717 if ((addr->addr == NULL) && (addr->netmask == NULL) &&
2718 (addr->broadaddr == NULL) && (addr->dstaddr == NULL))
2719 {
2720 /*
2721 * None of the addresses are IPv4 or IPv6
2722 * addresses, so throw this entry away.
2723 */
2724 free(addr);
2725 }
2726 else
2727 {
2728 /*
2729 * Add this entry to the list.
2730 */
2731 if (prevaddr == NULL)
2732 {
2733 dev->addresses = addr;
2734 }
2735 else
2736 {
2737 prevaddr->next = addr;
2738 }
2739 prevaddr = addr;
2740 }
2741 }
2742 }
2743
2744 /* Discard the rest of the message. */
2745 if (rpcap_discard(sockctrl, ssl, plen, errbuf) == 1)
2746 goto error_nodiscard;
2747
2748 /* Control connection has to be closed only in case the remote machine is in passive mode */
2749 if (!active)
2750 {
2751 /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2752 #ifdef HAVE_OPENSSL
2753 if (ssl)
2754 {
2755 // Finish using the SSL handle for the socket.
2756 // This must be done *before* the socket is closed.
2757 ssl_finish(ssl);
2758 }
2759 #endif
2760 if (sock_close(sockctrl, errbuf, PCAP_ERRBUF_SIZE))
2761 return -1;
2762 }
2763
2764 /* To avoid inconsistencies in the number of sock_init() */
2765 sock_cleanup();
2766
2767 return 0;
2768
2769 error:
2770 /*
2771 * In case there has been an error, I don't want to overwrite it with a new one
2772 * if the following call fails. I want to return always the original error.
2773 *
2774 * Take care: this connection can already be closed when we try to close it.
2775 * This happens because a previous error in the rpcapd, which requested to
2776 * closed the connection. In that case, we already recognized that into the
2777 * rpspck_isheaderok() and we already acknowledged the closing.
2778 * In that sense, this call is useless here (however it is needed in case
2779 * the client generates the error).
2780 *
2781 * Checks if all the data has been read; if not, discard the data in excess
2782 */
2783 (void) rpcap_discard(sockctrl, ssl, plen, NULL);
2784
2785 error_nodiscard:
2786 /* Control connection has to be closed only in case the remote machine is in passive mode */
2787 if (!active)
2788 {
2789 #ifdef HAVE_OPENSSL
2790 if (ssl)
2791 {
2792 // Finish using the SSL handle for the socket.
2793 // This must be done *before* the socket is closed.
2794 ssl_finish(ssl);
2795 }
2796 #endif
2797 sock_close(sockctrl, NULL, 0);
2798 }
2799
2800 /* To avoid inconsistencies in the number of sock_init() */
2801 sock_cleanup();
2802
2803 /* Free whatever interfaces we've allocated. */
2804 pcap_freealldevs(*alldevs);
2805
2806 return -1;
2807 }
2808
2809 /*
2810 * Active mode routines.
2811 *
2812 * The old libpcap API is somewhat ugly, and makes active mode difficult
2813 * to implement; we provide some APIs for it that work only with rpcap.
2814 */
2815
2816 SOCKET pcap_remoteact_accept_ex(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, int uses_ssl, char *errbuf)
2817 {
2818 /* socket-related variables */
2819 struct addrinfo hints; /* temporary struct to keep settings needed to open the new socket */
2820 struct addrinfo *addrinfo; /* keeps the addrinfo chain; required to open a new socket */
2821 struct sockaddr_storage from; /* generic sockaddr_storage variable */
2822 socklen_t fromlen; /* keeps the length of the sockaddr_storage variable */
2823 SOCKET sockctrl; /* keeps the main socket identifier */
2824 SSL *ssl = NULL; /* Optional SSL handler for sockctrl */
2825 uint8 protocol_version; /* negotiated protocol version */
2826 struct activehosts *temp, *prev; /* temp var needed to scan he host list chain */
2827
2828 *connectinghost = 0; /* just in case */
2829
2830 /* Prepare to open a new server socket */
2831 memset(&hints, 0, sizeof(struct addrinfo));
2832 /* WARNING Currently it supports only ONE socket family among ipv4 and IPv6 */
2833 hints.ai_family = AF_INET; /* PF_UNSPEC to have both IPv4 and IPv6 server */
2834 hints.ai_flags = AI_PASSIVE; /* Ready to a bind() socket */
2835 hints.ai_socktype = SOCK_STREAM;
2836
2837 /* Warning: this call can be the first one called by the user. */
2838 /* For this reason, we have to initialize the Winsock support. */
2839 if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
2840 return (SOCKET)-1;
2841
2842 /* Do the work */
2843 if ((port == NULL) || (port[0] == 0))
2844 {
2845 if (sock_initaddress(address, RPCAP_DEFAULT_NETPORT_ACTIVE, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2846 {
2847 return (SOCKET)-2;
2848 }
2849 }
2850 else
2851 {
2852 if (sock_initaddress(address, port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2853 {
2854 return (SOCKET)-2;
2855 }
2856 }
2857
2858
2859 if ((sockmain = sock_open(addrinfo, SOCKOPEN_SERVER, 1, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
2860 {
2861 freeaddrinfo(addrinfo);
2862 return (SOCKET)-2;
2863 }
2864 freeaddrinfo(addrinfo);
2865
2866 /* Connection creation */
2867 fromlen = sizeof(struct sockaddr_storage);
2868
2869 sockctrl = accept(sockmain, (struct sockaddr *) &from, &fromlen);
2870
2871 /* We're not using sock_close, since we do not want to send a shutdown */
2872 /* (which is not allowed on a non-connected socket) */
2873 closesocket(sockmain);
2874 sockmain = 0;
2875
2876 if (sockctrl == INVALID_SOCKET)
2877 {
2878 sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
2879 return (SOCKET)-2;
2880 }
2881
2882 /* Promote to SSL early before any error message may be sent */
2883 if (uses_ssl)
2884 {
2885 #ifdef HAVE_OPENSSL
2886 ssl = ssl_promotion(0, sockctrl, errbuf, PCAP_ERRBUF_SIZE);
2887 if (! ssl)
2888 {
2889 sock_close(sockctrl, NULL, 0);
2890 return (SOCKET)-1;
2891 }
2892 #else
2893 snprintf(errbuf, PCAP_ERRBUF_SIZE, "No TLS support");
2894 sock_close(sockctrl, NULL, 0);
2895 return (SOCKET)-1;
2896 #endif
2897 }
2898
2899 /* Get the numeric for of the name of the connecting host */
2900 if (getnameinfo((struct sockaddr *) &from, fromlen, connectinghost, RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST))
2901 {
2902 sock_geterror("getnameinfo()", errbuf, PCAP_ERRBUF_SIZE);
2903 rpcap_senderror(sockctrl, ssl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2904 #ifdef HAVE_OPENSSL
2905 if (ssl)
2906 {
2907 // Finish using the SSL handle for the socket.
2908 // This must be done *before* the socket is closed.
2909 ssl_finish(ssl);
2910 }
2911 #endif
2912 sock_close(sockctrl, NULL, 0);
2913 return (SOCKET)-1;
2914 }
2915
2916 /* checks if the connecting host is among the ones allowed */
2917 if (sock_check_hostlist((char *)hostlist, RPCAP_HOSTLIST_SEP, &from, errbuf, PCAP_ERRBUF_SIZE) < 0)
2918 {
2919 rpcap_senderror(sockctrl, ssl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2920 #ifdef HAVE_OPENSSL
2921 if (ssl)
2922 {
2923 // Finish using the SSL handle for the socket.
2924 // This must be done *before* the socket is closed.
2925 ssl_finish(ssl);
2926 }
2927 #endif
2928 sock_close(sockctrl, NULL, 0);
2929 return (SOCKET)-1;
2930 }
2931
2932 /*
2933 * Send authentication to the remote machine.
2934 */
2935 if (rpcap_doauth(sockctrl, ssl, &protocol_version, auth, errbuf) == -1)
2936 {
2937 /* Unrecoverable error. */
2938 rpcap_senderror(sockctrl, ssl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2939 #ifdef HAVE_OPENSSL
2940 if (ssl)
2941 {
2942 // Finish using the SSL handle for the socket.
2943 // This must be done *before* the socket is closed.
2944 ssl_finish(ssl);
2945 }
2946 #endif
2947 sock_close(sockctrl, NULL, 0);
2948 return (SOCKET)-3;
2949 }
2950
2951 /* Checks that this host does not already have a cntrl connection in place */
2952
2953 /* Initialize pointers */
2954 temp = activeHosts;
2955 prev = NULL;
2956
2957 while (temp)
2958 {
2959 /* This host already has an active connection in place, so I don't have to update the host list */
2960 if (sock_cmpaddr(&temp->host, &from) == 0)
2961 return sockctrl;
2962
2963 prev = temp;
2964 temp = temp->next;
2965 }
2966
2967 /* The host does not exist in the list; so I have to update the list */
2968 if (prev)
2969 {
2970 prev->next = (struct activehosts *) malloc(sizeof(struct activehosts));
2971 temp = prev->next;
2972 }
2973 else
2974 {
2975 activeHosts = (struct activehosts *) malloc(sizeof(struct activehosts));
2976 temp = activeHosts;
2977 }
2978
2979 if (temp == NULL)
2980 {
2981 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2982 errno, "malloc() failed");
2983 rpcap_senderror(sockctrl, ssl, protocol_version, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2984 #ifdef HAVE_OPENSSL
2985 if (ssl)
2986 {
2987 // Finish using the SSL handle for the socket.
2988 // This must be done *before* the socket is closed.
2989 ssl_finish(ssl);
2990 }
2991 #endif
2992 sock_close(sockctrl, NULL, 0);
2993 return (SOCKET)-1;
2994 }
2995
2996 memcpy(&temp->host, &from, fromlen);
2997 temp->sockctrl = sockctrl;
2998 temp->ssl = ssl;
2999 temp->protocol_version = protocol_version;
3000 temp->next = NULL;
3001
3002 return sockctrl;
3003 }
3004
3005 SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf)
3006 {
3007 return pcap_remoteact_accept_ex(address, port, hostlist, connectinghost, auth, 0, errbuf);
3008 }
3009
3010 int pcap_remoteact_close(const char *host, char *errbuf)
3011 {
3012 struct activehosts *temp, *prev; /* temp var needed to scan the host list chain */
3013 struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
3014 int retval;
3015
3016 temp = activeHosts;
3017 prev = NULL;
3018
3019 /* retrieve the network address corresponding to 'host' */
3020 addrinfo = NULL;
3021 memset(&hints, 0, sizeof(struct addrinfo));
3022 hints.ai_family = PF_UNSPEC;
3023 hints.ai_socktype = SOCK_STREAM;
3024
3025 retval = sock_initaddress(host, "0", &hints, &addrinfo, errbuf,
3026 PCAP_ERRBUF_SIZE);
3027 if (retval != 0)
3028 {
3029 return -1;
3030 }
3031
3032 while (temp)
3033 {
3034 ai_next = addrinfo;
3035 while (ai_next)
3036 {
3037 if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
3038 {
3039 struct rpcap_header header;
3040 int status = 0;
3041
3042 /* Close this connection */
3043 rpcap_createhdr(&header, temp->protocol_version,
3044 RPCAP_MSG_CLOSE, 0, 0);
3045
3046 /*
3047 * Don't check for errors, since we're
3048 * just cleaning up.
3049 */
3050 if (sock_send(temp->sockctrl, temp->ssl,
3051 (char *)&header,
3052 sizeof(struct rpcap_header), errbuf,
3053 PCAP_ERRBUF_SIZE) < 0)
3054 {
3055 /*
3056 * Let that error be the one we
3057 * report.
3058 */
3059 #ifdef HAVE_OPENSSL
3060 if (temp->ssl)
3061 {
3062 // Finish using the SSL handle
3063 // for the socket.
3064 // This must be done *before*
3065 // the socket is closed.
3066 ssl_finish(temp->ssl);
3067 }
3068 #endif
3069 (void)sock_close(temp->sockctrl, NULL,
3070 0);
3071 status = -1;
3072 }
3073 else
3074 {
3075 #ifdef HAVE_OPENSSL
3076 if (temp->ssl)
3077 {
3078 // Finish using the SSL handle
3079 // for the socket.
3080 // This must be done *before*
3081 // the socket is closed.
3082 ssl_finish(temp->ssl);
3083 }
3084 #endif
3085 if (sock_close(temp->sockctrl, errbuf,
3086 PCAP_ERRBUF_SIZE) == -1)
3087 status = -1;
3088 }
3089
3090 /*
3091 * Remove the host from the list of active
3092 * hosts.
3093 */
3094 if (prev)
3095 prev->next = temp->next;
3096 else
3097 activeHosts = temp->next;
3098
3099 freeaddrinfo(addrinfo);
3100
3101 free(temp);
3102
3103 /* To avoid inconsistencies in the number of sock_init() */
3104 sock_cleanup();
3105
3106 return status;
3107 }
3108
3109 ai_next = ai_next->ai_next;
3110 }
3111 prev = temp;
3112 temp = temp->next;
3113 }
3114
3115 if (addrinfo)
3116 freeaddrinfo(addrinfo);
3117
3118 /* To avoid inconsistencies in the number of sock_init() */
3119 sock_cleanup();
3120
3121 snprintf(errbuf, PCAP_ERRBUF_SIZE, "The host you want to close the active connection is not known");
3122 return -1;
3123 }
3124
3125 void pcap_remoteact_cleanup(void)
3126 {
3127 # ifdef HAVE_OPENSSL
3128 if (ssl_main)
3129 {
3130 // Finish using the SSL handle for the main active socket.
3131 // This must be done *before* the socket is closed.
3132 ssl_finish(ssl_main);
3133 ssl_main = NULL;
3134 }
3135 # endif
3136
3137 /* Very dirty, but it works */
3138 if (sockmain)
3139 {
3140 closesocket(sockmain);
3141
3142 /* To avoid inconsistencies in the number of sock_init() */
3143 sock_cleanup();
3144 }
3145 }
3146
3147 int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf)
3148 {
3149 struct activehosts *temp; /* temp var needed to scan the host list chain */
3150 size_t len;
3151 char hoststr[RPCAP_HOSTLIST_SIZE + 1];
3152
3153 temp = activeHosts;
3154
3155 len = 0;
3156 *hostlist = 0;
3157
3158 while (temp)
3159 {
3160 /*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
3161
3162 /* Get the numeric form of the name of the connecting host */
3163 if (sock_getascii_addrport((struct sockaddr_storage *) &temp->host, hoststr,
3164 RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST, errbuf, PCAP_ERRBUF_SIZE) != -1)
3165 /* if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
3166 /* RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
3167 {
3168 /* sock_geterror("getnameinfo()", errbuf, PCAP_ERRBUF_SIZE); */
3169 return -1;
3170 }
3171
3172 len = len + strlen(hoststr) + 1 /* the separator */;
3173
3174 if ((size < 0) || (len >= (size_t)size))
3175 {
3176 snprintf(errbuf, PCAP_ERRBUF_SIZE, "The string you provided is not able to keep "
3177 "the hostnames for all the active connections");
3178 return -1;
3179 }
3180
3181 pcap_strlcat(hostlist, hoststr, PCAP_ERRBUF_SIZE);
3182 hostlist[len - 1] = sep;
3183 hostlist[len] = 0;
3184
3185 temp = temp->next;
3186 }
3187
3188 return 0;
3189 }
3190
3191 /*
3192 * Receive the header of a message.
3193 */
3194 static int rpcap_recv_msg_header(SOCKET sock, SSL *ssl, struct rpcap_header *header, char *errbuf)
3195 {
3196 int nrecv;
3197
3198 nrecv = sock_recv(sock, ssl, (char *) header, sizeof(struct rpcap_header),
3199 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
3200 PCAP_ERRBUF_SIZE);
3201 if (nrecv == -1)
3202 {
3203 /* Network error. */
3204 return -1;
3205 }
3206 header->plen = ntohl(header->plen);
3207 return 0;
3208 }
3209
3210 /*
3211 * Make sure the protocol version of a received message is what we were
3212 * expecting.
3213 */
3214 static int rpcap_check_msg_ver(SOCKET sock, SSL *ssl, uint8 expected_ver, struct rpcap_header *header, char *errbuf)
3215 {
3216 /*
3217 * Did the server specify the version we negotiated?
3218 */
3219 if (header->ver != expected_ver)
3220 {
3221 /*
3222 * Discard the rest of the message.
3223 */
3224 if (rpcap_discard(sock, ssl, header->plen, errbuf) == -1)
3225 return -1;
3226
3227 /*
3228 * Tell our caller that it's not the negotiated version.
3229 */
3230 if (errbuf != NULL)
3231 {
3232 snprintf(errbuf, PCAP_ERRBUF_SIZE,
3233 "Server sent us a message with version %u when we were expecting %u",
3234 header->ver, expected_ver);
3235 }
3236 return -1;
3237 }
3238 return 0;
3239 }
3240
3241 /*
3242 * Check the message type of a received message, which should either be
3243 * the expected message type or RPCAP_MSG_ERROR.
3244 */
3245 static int rpcap_check_msg_type(SOCKET sock, SSL *ssl, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf)
3246 {
3247 const char *request_type_string;
3248 const char *msg_type_string;
3249
3250 /*
3251 * What type of message is it?
3252 */
3253 if (header->type == RPCAP_MSG_ERROR)
3254 {
3255 /*
3256 * The server reported an error.
3257 * Hand that error back to our caller.
3258 */
3259 *errcode = ntohs(header->value);
3260 rpcap_msg_err(sock, ssl, header->plen, errbuf);
3261 return -1;
3262 }
3263
3264 *errcode = 0;
3265
3266 /*
3267 * For a given request type value, the expected reply type value
3268 * is the request type value with ORed with RPCAP_MSG_IS_REPLY.
3269 */
3270 if (header->type != (request_type | RPCAP_MSG_IS_REPLY))
3271 {
3272 /*
3273 * This isn't a reply to the request we sent.
3274 */
3275
3276 /*
3277 * Discard the rest of the message.
3278 */
3279 if (rpcap_discard(sock, ssl, header->plen, errbuf) == -1)
3280 return -1;
3281
3282 /*
3283 * Tell our caller about it.
3284 */
3285 request_type_string = rpcap_msg_type_string(request_type);
3286 msg_type_string = rpcap_msg_type_string(header->type);
3287 if (errbuf != NULL)
3288 {
3289 if (request_type_string == NULL)
3290 {
3291 /* This should not happen. */
3292 snprintf(errbuf, PCAP_ERRBUF_SIZE,
3293 "rpcap_check_msg_type called for request message with type %u",
3294 request_type);
3295 return -1;
3296 }
3297 if (msg_type_string != NULL)
3298 snprintf(errbuf, PCAP_ERRBUF_SIZE,
3299 "%s message received in response to a %s message",
3300 msg_type_string, request_type_string);
3301 else
3302 snprintf(errbuf, PCAP_ERRBUF_SIZE,
3303 "Message of unknown type %u message received in response to a %s request",
3304 header->type, request_type_string);
3305 }
3306 return -1;
3307 }
3308
3309 return 0;
3310 }
3311
3312 /*
3313 * Receive and process the header of a message.
3314 */
3315 static int rpcap_process_msg_header(SOCKET sock, SSL *ssl, uint8 expected_ver, uint8 request_type, struct rpcap_header *header, char *errbuf)
3316 {
3317 uint16 errcode;
3318
3319 if (rpcap_recv_msg_header(sock, ssl, header, errbuf) == -1)
3320 {
3321 /* Network error. */
3322 return -1;
3323 }
3324
3325 /*
3326 * Did the server specify the version we negotiated?
3327 */
3328 if (rpcap_check_msg_ver(sock, ssl, expected_ver, header, errbuf) == -1)
3329 return -1;
3330
3331 /*
3332 * Check the message type.
3333 */
3334 return rpcap_check_msg_type(sock, ssl, request_type, header,
3335 &errcode, errbuf);
3336 }
3337
3338 /*
3339 * Read data from a message.
3340 * If we're trying to read more data that remains, puts an error
3341 * message into errmsgbuf and returns -2. Otherwise, tries to read
3342 * the data and, if that succeeds, subtracts the amount read from
3343 * the number of bytes of data that remains.
3344 * Returns 0 on success, logs a message and returns -1 on a network
3345 * error.
3346 */
3347 static int rpcap_recv(SOCKET sock, SSL *ssl, void *buffer, size_t toread, uint32 *plen, char *errbuf)
3348 {
3349 int nread;
3350
3351 if (toread > *plen)
3352 {
3353 /* The server sent us a bad message */
3354 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
3355 return -1;
3356 }
3357 nread = sock_recv(sock, ssl, buffer, toread,
3358 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
3359 if (nread == -1)
3360 {
3361 return -1;
3362 }
3363 *plen -= nread;
3364 return 0;
3365 }
3366
3367 /*
3368 * This handles the RPCAP_MSG_ERROR message.
3369 */
3370 static void rpcap_msg_err(SOCKET sockctrl, SSL *ssl, uint32 plen, char *remote_errbuf)
3371 {
3372 char errbuf[PCAP_ERRBUF_SIZE];
3373
3374 if (plen >= PCAP_ERRBUF_SIZE)
3375 {
3376 /*
3377 * Message is too long; just read as much of it as we
3378 * can into the buffer provided, and discard the rest.
3379 */
3380 if (sock_recv(sockctrl, ssl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
3381 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
3382 PCAP_ERRBUF_SIZE) == -1)
3383 {
3384 // Network error.
3385 DIAG_OFF_FORMAT_TRUNCATION
3386 snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
3387 DIAG_ON_FORMAT_TRUNCATION
3388 return;
3389 }
3390
3391 /*
3392 * Null-terminate it.
3393 */
3394 remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
3395
3396 #ifdef _WIN32
3397 /*
3398 * If we're not in UTF-8 mode, convert it to the local
3399 * code page.
3400 */
3401 if (!pcap_utf_8_mode)
3402 utf_8_to_acp_truncated(remote_errbuf);
3403 #endif
3404
3405 /*
3406 * Throw away the rest.
3407 */
3408 (void)rpcap_discard(sockctrl, ssl, plen - (PCAP_ERRBUF_SIZE - 1), remote_errbuf);
3409 }
3410 else if (plen == 0)
3411 {
3412 /* Empty error string. */
3413 remote_errbuf[0] = '\0';
3414 }
3415 else
3416 {
3417 if (sock_recv(sockctrl, ssl, remote_errbuf, plen,
3418 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
3419 PCAP_ERRBUF_SIZE) == -1)
3420 {
3421 // Network error.
3422 DIAG_OFF_FORMAT_TRUNCATION
3423 snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
3424 DIAG_ON_FORMAT_TRUNCATION
3425 return;
3426 }
3427
3428 /*
3429 * Null-terminate it.
3430 */
3431 remote_errbuf[plen] = '\0';
3432 }
3433 }
3434
3435 /*
3436 * Discard data from a connection.
3437 * Mostly used to discard wrong-sized messages.
3438 * Returns 0 on success, logs a message and returns -1 on a network
3439 * error.
3440 */
3441 static int rpcap_discard(SOCKET sock, SSL *ssl, uint32 len, char *errbuf)
3442 {
3443 if (len != 0)
3444 {
3445 if (sock_discard(sock, ssl, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
3446 {
3447 // Network error.
3448 return -1;
3449 }
3450 }
3451 return 0;
3452 }
3453
3454 /*
3455 * Read bytes into the pcap_t's buffer until we have the specified
3456 * number of bytes read or we get an error or interrupt indication.
3457 */
3458 static int rpcap_read_packet_msg(struct pcap_rpcap const *rp, pcap_t *p, size_t size)
3459 {
3460 u_char *bp;
3461 int cc;
3462 int bytes_read;
3463
3464 bp = p->bp;
3465 cc = p->cc;
3466
3467 /*
3468 * Loop until we have the amount of data requested or we get
3469 * an error or interrupt.
3470 */
3471 while ((size_t)cc < size)
3472 {
3473 /*
3474 * We haven't read all of the packet header yet.
3475 * Read what remains, which could be all of it.
3476 */
3477 bytes_read = sock_recv(rp->rmt_sockdata, rp->data_ssl, bp, size - cc,
3478 SOCK_RECEIVEALL_NO|SOCK_EOF_IS_ERROR, p->errbuf,
3479 PCAP_ERRBUF_SIZE);
3480
3481 if (bytes_read == -1)
3482 {
3483 /*
3484 * Network error. Update the read pointer and
3485 * byte count, and return an error indication.
3486 */
3487 p->bp = bp;
3488 p->cc = cc;
3489 return -1;
3490 }
3491 if (bytes_read == -3)
3492 {
3493 /*
3494 * Interrupted receive. Update the read
3495 * pointer and byte count, and return
3496 * an interrupted indication.
3497 */
3498 p->bp = bp;
3499 p->cc = cc;
3500 return -3;
3501 }
3502 if (bytes_read == 0)
3503 {
3504 /*
3505 * EOF - server terminated the connection.
3506 * Update the read pointer and byte count, and
3507 * return an error indication.
3508 */
3509 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
3510 "The server terminated the connection.");
3511 return -1;
3512 }
3513 bp += bytes_read;
3514 cc += bytes_read;
3515 }
3516 p->bp = bp;
3517 p->cc = cc;
3518 return 0;
3519 }