iptables: use flock() instead of abstract unix sockets
Pablo Neira Ayuso
maintainerPATCH 1/1 iptables: use flock() instead of abstract unix sockets
Abstract unix sockets cannot be used to synchronize several concurrent instances of iptables since an unpriviledged process can create them and prevent the legitimate iptables instance from running.
Use flock() and /run instead as suggested by Lennart Poettering.
--- iptables/xshared.c | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-)
iptables/xshared.c +7 -15
@@ -9,11 +9,11 @@#include <sys/socket.h> #include <sys/un.h> #include <unistd.h> +#include <fcntl.h> #include <xtables.h> #include "xshared.h" -#define XT_SOCKET_NAME "xtables" -#define XT_SOCKET_LEN 8 +#define XT_LOCK_NAME "/run/xtables.lock"/* * Print out any special helps. A user might like to be able to add a --help
@@ -245,22 +245,14 @@ void xs_init_match(struct xtables_match *match)bool xtables_lock (int wait) { -int i =0 , ret, xt_socket; -struct sockaddr_un xt_addr; -int waited =0 ; - -memset (&xt_addr,0 ,sizeof (xt_addr)); - xt_addr.sun_family =AF_UNIX ; -strcpy (xt_addr.sun_path+1 ,XT_SOCKET_NAME ); - xt_socket =socket (AF_UNIX ,SOCK_STREAM ,0 ); -/* If we can't even create a socket, fall back to prior (lockless) behavior */ -if (xt_socket <0 ) +int fd, waited =0 , i =0 ; + + fd =open (XT_LOCK_NAME ,O_CREAT ,0600 ); +if (fd <0 )return true;while (1 ) { - ret =bind (xt_socket, (struct sockaddr *)&xt_addr, - offsetof(struct sockaddr_un , sun_path)+XT_SOCKET_LEN ); -if (ret ==0 ) +if (flock (fd,LOCK_EX |LOCK_NB ) ==0 )return true;else if (wait >=0 && waited >= wait)return false;
Signature · 1 line
1.7.10.4
Quoted 5 lines · Pablo Neira Ayuso
Abstract unix sockets cannot be used to synchronize several concurrent instances of iptables since an unpriviledged process can create them and prevent the legitimate iptables instance from running.
Use
flock()and /run instead as suggested by Lennart Poettering.
Looks OK. Of course, it's a bit nasty to do the sleep() loop, but there is no time-limited version of flock(), hence doing the sleep() loop is kinda necessary, unless one wants to use SIGARLM, but that's awful to do without races...
Hence, looks OK to me.
A minor optimization might be to move the lock file into its own subdir /run/iptables/ or so, but it's OK if you don't.
Lennart
Signature · 1 line
Lennart Poettering, Red Hat
Quoted 8 lines · Pablo Neira Ayuso
Abstract unix sockets cannot be used to synchronize several concurrent instances of iptables since an unpriviledged process can create them and prevent the legitimate iptables instance from running.
Use
flock()and /run instead as suggested by Lennart Poettering.Fixes 93587a0 ("ip[6]tables: Add locking to prevent concurrent instances")Reported-by Lennart Poettering <[email protected]>
Looks good Pablo. Thanks for finding this Lennart.
Phil