blob: cdb3e40b9d14ee28095fb02a088154a8989996c4 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001filter.txt: Linux Socket Filtering
2Written by: Jay Schulist <jschlst@samba.org>
3
4Introduction
5============
6
7 Linux Socket Filtering is derived from the Berkeley
8Packet Filter. There are some distinct differences between
9the BSD and Linux Kernel Filtering.
10
11Linux Socket Filtering (LSF) allows a user-space program to
12attach a filter onto any socket and allow or disallow certain
13types of data to come through the socket. LSF follows exactly
14the same filter code structure as the BSD Berkeley Packet Filter
15(BPF), so referring to the BSD bpf.4 manpage is very helpful in
16creating filters.
17
18LSF is much simpler than BPF. One does not have to worry about
19devices or anything like that. You simply create your filter
Vincent Bernatd59577b2013-01-16 22:55:49 +010020code, send it to the kernel via the SO_ATTACH_FILTER option and
Linus Torvalds1da177e2005-04-16 15:20:36 -070021if your filter code passes the kernel check on it, you then
22immediately begin filtering data on that socket.
23
24You can also detach filters from your socket via the
Vincent Bernatd59577b2013-01-16 22:55:49 +010025SO_DETACH_FILTER option. This will probably not be used much
Linus Torvalds1da177e2005-04-16 15:20:36 -070026since when you close a socket that has a filter on it the
27filter is automagically removed. The other less common case
28may be adding a different filter on the same socket where you had another
29filter that is still running: the kernel takes care of removing
30the old one and placing your new one in its place, assuming your
31filter has passed the checks, otherwise if it fails the old filter
32will remain on that socket.
33
Vincent Bernatd59577b2013-01-16 22:55:49 +010034SO_LOCK_FILTER option allows to lock the filter attached to a
35socket. Once set, a filter cannot be removed or changed. This allows
36one process to setup a socket, attach a filter, lock it then drop
37privileges and be assured that the filter will be kept until the
38socket is closed.
39
Linus Torvalds1da177e2005-04-16 15:20:36 -070040Examples
41========
42
43Ioctls-
44setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &Filter, sizeof(Filter));
45setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &value, sizeof(value));
Vincent Bernatd59577b2013-01-16 22:55:49 +010046setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER, &value, sizeof(value));
Linus Torvalds1da177e2005-04-16 15:20:36 -070047
48See the BSD bpf.4 manpage and the BSD Packet Filter paper written by
49Steven McCanne and Van Jacobson of Lawrence Berkeley Laboratory.