1 /*
2  * Copyright (c) 2006 Paolo Abeni (Italy)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote
15  * products derived from this software without specific prior written
16  * permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Bluetooth sniffing API implementation for Linux platform
31  * By Paolo Abeni <paolo.abeni@email.it>
32  *
33  */
34 
35 #ifdef HAVE_CONFIG_H
36 #include "config.h"
37 #endif
38 
39 #include "pcap-int.h"
40 #include "pcap-bt-linux.h"
41 #include "pcap/bluetooth.h"
42 
43 #ifdef NEED_STRERROR_H
44 #include "strerror.h"
45 #endif
46 
47 #include <errno.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include <fcntl.h>
51 #include <string.h>
52 #include <sys/ioctl.h>
53 #include <sys/socket.h>
54 #include <arpa/inet.h>
55 
56 #include <bluetooth/bluetooth.h>
57 #include <bluetooth/hci.h>
58 
59 #define BT_IFACE "bluetooth"
60 #define BT_CTRL_SIZE 128
61 
62 /* forward declaration */
63 static int bt_activate(pcap_t *);
64 static int bt_read_linux(pcap_t *, int , pcap_handler , u_char *);
65 static int bt_inject_linux(pcap_t *, const void *, size_t);
66 static int bt_setdirection_linux(pcap_t *, pcap_direction_t);
67 static int bt_stats_linux(pcap_t *, struct pcap_stat *);
68 
69 /*
70  * Private data for capturing on Linux Bluetooth devices.
71  */
72 struct pcap_bt {
73 	int dev_id;		/* device ID of device we're bound to */
74 };
75 
76 int
bt_findalldevs(pcap_if_t ** alldevsp,char * err_str)77 bt_findalldevs(pcap_if_t **alldevsp, char *err_str)
78 {
79 	struct hci_dev_list_req *dev_list;
80 	struct hci_dev_req *dev_req;
81 	int i, sock;
82 	int ret = 0;
83 
84 	sock  = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
85 	if (sock < 0)
86 	{
87 		/* if bluetooth is not supported this this is not fatal*/
88 		if (errno == EAFNOSUPPORT)
89 			return 0;
90 		snprintf(err_str, PCAP_ERRBUF_SIZE,
91 		    "Can't open raw Bluetooth socket: %s", strerror(errno));
92 		return -1;
93 	}
94 
95 	dev_list = malloc(HCI_MAX_DEV * sizeof(*dev_req) + sizeof(*dev_list));
96 	if (!dev_list)
97 	{
98 		snprintf(err_str, PCAP_ERRBUF_SIZE, "Can't allocate %zu bytes for Bluetooth device list",
99 			HCI_MAX_DEV * sizeof(*dev_req) + sizeof(*dev_list));
100 		ret = -1;
101 		goto done;
102 	}
103 
104 	dev_list->dev_num = HCI_MAX_DEV;
105 
106 	if (ioctl(sock, HCIGETDEVLIST, (void *) dev_list) < 0)
107 	{
108 		snprintf(err_str, PCAP_ERRBUF_SIZE,
109 		    "Can't get Bluetooth device list via ioctl: %s",
110 		    strerror(errno));
111 		ret = -1;
112 		goto free;
113 	}
114 
115 	dev_req = dev_list->dev_req;
116 	for (i = 0; i < dev_list->dev_num; i++, dev_req++) {
117 		char dev_name[20], dev_descr[30];
118 
119 		snprintf(dev_name, 20, BT_IFACE"%d", dev_req->dev_id);
120 		snprintf(dev_descr, 30, "Bluetooth adapter number %d", i);
121 
122 		if (pcap_add_if(alldevsp, dev_name, 0,
123 		       dev_descr, err_str) < 0)
124 		{
125 			ret = -1;
126 			break;
127 		}
128 
129 	}
130 
131 free:
132 	free(dev_list);
133 
134 done:
135 	close(sock);
136 	return ret;
137 }
138 
139 pcap_t *
bt_create(const char * device,char * ebuf,int * is_ours)140 bt_create(const char *device, char *ebuf, int *is_ours)
141 {
142 	const char *cp;
143 	char *cpend;
144 	long devnum;
145 	pcap_t *p;
146 
147 	/* Does this look like a Bluetooth device? */
148 	cp = strrchr(device, '/');
149 	if (cp == NULL)
150 		cp = device;
151 	/* Does it begin with BT_IFACE? */
152 	if (strncmp(cp, BT_IFACE, sizeof BT_IFACE - 1) != 0) {
153 		/* Nope, doesn't begin with BT_IFACE */
154 		*is_ours = 0;
155 		return NULL;
156 	}
157 	/* Yes - is BT_IFACE followed by a number? */
158 	cp += sizeof BT_IFACE - 1;
159 	devnum = strtol(cp, &cpend, 10);
160 	if (cpend == cp || *cpend != '\0') {
161 		/* Not followed by a number. */
162 		*is_ours = 0;
163 		return NULL;
164 	}
165 	if (devnum < 0) {
166 		/* Followed by a non-valid number. */
167 		*is_ours = 0;
168 		return NULL;
169 	}
170 
171 	/* OK, it's probably ours. */
172 	*is_ours = 1;
173 
174 	p = pcap_create_common(device, ebuf, sizeof (struct pcap_bt));
175 	if (p == NULL)
176 		return (NULL);
177 
178 	p->activate_op = bt_activate;
179 	return (p);
180 }
181 
182 static int
bt_activate(pcap_t * handle)183 bt_activate(pcap_t* handle)
184 {
185 	struct pcap_bt *handlep = handle->priv;
186 	struct sockaddr_hci addr;
187 	int opt;
188 	int		dev_id;
189 	struct hci_filter	flt;
190 	int err = PCAP_ERROR;
191 
192 	/* get bt interface id */
193 	if (sscanf(handle->opt.source, BT_IFACE"%d", &dev_id) != 1)
194 	{
195 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
196 			"Can't get Bluetooth device index from %s",
197 			 handle->opt.source);
198 		return PCAP_ERROR;
199 	}
200 
201 	/* Initialize some components of the pcap structure. */
202 	handle->bufsize = handle->snapshot+BT_CTRL_SIZE+sizeof(pcap_bluetooth_h4_header);
203 	handle->offset = BT_CTRL_SIZE;
204 	handle->linktype = DLT_BLUETOOTH_HCI_H4_WITH_PHDR;
205 
206 	handle->read_op = bt_read_linux;
207 	handle->inject_op = bt_inject_linux;
208 	handle->setfilter_op = install_bpf_program; /* no kernel filtering */
209 	handle->setdirection_op = bt_setdirection_linux;
210 	handle->set_datalink_op = NULL;	/* can't change data link type */
211 	handle->getnonblock_op = pcap_getnonblock_fd;
212 	handle->setnonblock_op = pcap_setnonblock_fd;
213 	handle->stats_op = bt_stats_linux;
214 	handlep->dev_id = dev_id;
215 
216 	/* Create HCI socket */
217 	handle->fd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
218 	if (handle->fd < 0) {
219 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
220 		    "Can't create raw socket: %s", strerror(errno));
221 		return PCAP_ERROR;
222 	}
223 
224 	handle->buffer = malloc(handle->bufsize);
225 	if (!handle->buffer) {
226 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't allocate dump buffer: %s",
227 			pcap_strerror(errno));
228 		goto close_fail;
229 	}
230 
231 	opt = 1;
232 	if (setsockopt(handle->fd, SOL_HCI, HCI_DATA_DIR, &opt, sizeof(opt)) < 0) {
233 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
234 		    "Can't enable data direction info: %s", strerror(errno));
235 		goto close_fail;
236 	}
237 
238 	opt = 1;
239 	if (setsockopt(handle->fd, SOL_HCI, HCI_TIME_STAMP, &opt, sizeof(opt)) < 0) {
240 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
241 		    "Can't enable time stamp: %s", strerror(errno));
242 		goto close_fail;
243 	}
244 
245 	/* Setup filter, do not call hci function to avoid dependence on
246 	 * external libs	*/
247 	memset(&flt, 0, sizeof(flt));
248 	memset((void *) &flt.type_mask, 0xff, sizeof(flt.type_mask));
249 	memset((void *) &flt.event_mask, 0xff, sizeof(flt.event_mask));
250 	if (setsockopt(handle->fd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
251 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
252 		    "Can't set filter: %s", strerror(errno));
253 		goto close_fail;
254 	}
255 
256 
257 	/* Bind socket to the HCI device */
258 	addr.hci_family = AF_BLUETOOTH;
259 	addr.hci_dev = handlep->dev_id;
260 #ifdef SOCKADDR_HCI_HAS_HCI_CHANNEL
261 	addr.hci_channel = HCI_CHANNEL_RAW;
262 #endif
263 	if (bind(handle->fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
264 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
265 		    "Can't attach to device %d: %s", handlep->dev_id,
266 		    strerror(errno));
267 		goto close_fail;
268 	}
269 
270 	if (handle->opt.rfmon) {
271 		/*
272 		 * Monitor mode doesn't apply to Bluetooth devices.
273 		 */
274 		err = PCAP_ERROR_RFMON_NOTSUP;
275 		goto close_fail;
276 	}
277 
278 	if (handle->opt.buffer_size != 0) {
279 		/*
280 		 * Set the socket buffer size to the specified value.
281 		 */
282 		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
283 		    &handle->opt.buffer_size,
284 		    sizeof(handle->opt.buffer_size)) == -1) {
285 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
286 				 "SO_RCVBUF: %s", pcap_strerror(errno));
287 			goto close_fail;
288 		}
289 	}
290 
291 	handle->selectable_fd = handle->fd;
292 	return 0;
293 
294 close_fail:
295 	pcap_cleanup_live_common(handle);
296 	return err;
297 }
298 
299 static int
bt_read_linux(pcap_t * handle,int max_packets,pcap_handler callback,u_char * user)300 bt_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
301 {
302 	struct cmsghdr *cmsg;
303 	struct msghdr msg;
304 	struct iovec  iv;
305 	ssize_t ret;
306 	struct pcap_pkthdr pkth;
307 	pcap_bluetooth_h4_header* bthdr;
308 
309 	bthdr = (pcap_bluetooth_h4_header*) &handle->buffer[handle->offset];
310 	iv.iov_base = &handle->buffer[handle->offset+sizeof(pcap_bluetooth_h4_header)];
311 	iv.iov_len  = handle->snapshot;
312 
313 	memset(&msg, 0, sizeof(msg));
314 	msg.msg_iov = &iv;
315 	msg.msg_iovlen = 1;
316 	msg.msg_control = handle->buffer;
317 	msg.msg_controllen = handle->offset;
318 
319 	/* ignore interrupt system call error */
320 	do {
321 		ret = recvmsg(handle->fd, &msg, 0);
322 		if (handle->break_loop)
323 		{
324 			handle->break_loop = 0;
325 			return -2;
326 		}
327 	} while ((ret == -1) && (errno == EINTR));
328 
329 	if (ret < 0) {
330 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
331 		    "Can't receive packet: %s", strerror(errno));
332 		return -1;
333 	}
334 
335 	pkth.caplen = ret;
336 
337 	/* get direction and timestamp*/
338 	cmsg = CMSG_FIRSTHDR(&msg);
339 	int in=0;
340 	while (cmsg) {
341 		switch (cmsg->cmsg_type) {
342 			case HCI_CMSG_DIR:
343 				memcpy(&in, CMSG_DATA(cmsg), sizeof in);
344 				break;
345                       	case HCI_CMSG_TSTAMP:
346                       		memcpy(&pkth.ts, CMSG_DATA(cmsg),
347                       		    sizeof pkth.ts);
348 				break;
349 		}
350 		cmsg = CMSG_NXTHDR(&msg, cmsg);
351 	}
352 	if ((in && (handle->direction == PCAP_D_OUT)) ||
353 				((!in) && (handle->direction == PCAP_D_IN)))
354 		return 0;
355 
356 	bthdr->direction = htonl(in != 0);
357 	pkth.caplen+=sizeof(pcap_bluetooth_h4_header);
358 	pkth.len = pkth.caplen;
359 	if (handle->fcode.bf_insns == NULL ||
360 	    bpf_filter(handle->fcode.bf_insns, &handle->buffer[handle->offset],
361 	      pkth.len, pkth.caplen)) {
362 		callback(user, &pkth, &handle->buffer[handle->offset]);
363 		return 1;
364 	}
365 	return 0;	/* didn't pass filter */
366 }
367 
368 static int
bt_inject_linux(pcap_t * handle,const void * buf,size_t size)369 bt_inject_linux(pcap_t *handle, const void *buf, size_t size)
370 {
371 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on "
372     		"bluetooth devices");
373 	return (-1);
374 }
375 
376 
377 static int
bt_stats_linux(pcap_t * handle,struct pcap_stat * stats)378 bt_stats_linux(pcap_t *handle, struct pcap_stat *stats)
379 {
380 	struct pcap_bt *handlep = handle->priv;
381 	int ret;
382 	struct hci_dev_info dev_info;
383 	struct hci_dev_stats * s = &dev_info.stat;
384 	dev_info.dev_id = handlep->dev_id;
385 
386 	/* ignore eintr */
387 	do {
388 		ret = ioctl(handle->fd, HCIGETDEVINFO, (void *)&dev_info);
389 	} while ((ret == -1) && (errno == EINTR));
390 
391 	if (ret < 0) {
392 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
393 		    "Can't get stats via ioctl: %s", strerror(errno));
394 		return (-1);
395 
396 	}
397 
398 	/* we receive both rx and tx frames, so comulate all stats */
399 	stats->ps_recv = s->evt_rx + s->acl_rx + s->sco_rx + s->cmd_tx +
400 		s->acl_tx +s->sco_tx;
401 	stats->ps_drop = s->err_rx + s->err_tx;
402 	stats->ps_ifdrop = 0;
403 	return 0;
404 }
405 
406 static int
bt_setdirection_linux(pcap_t * p,pcap_direction_t d)407 bt_setdirection_linux(pcap_t *p, pcap_direction_t d)
408 {
409 	p->direction = d;
410 	return 0;
411 }
412