[vz7,2/2] tun: Add ioctl() SIOCGSKNS cmd to allow obtaining net ns of tun device

Submitted by Kirill Tkhai on March 22, 2018, 4:35 p.m.

Details

Message ID 152173651510.3038.12077049619335033814.stgit@localhost.localdomain
State New
Series "Port SIOCGSKNS support for sockets and tun"
Headers show

Commit Message

Kirill Tkhai March 22, 2018, 4:35 p.m.
Port ms commit f2780d6d7475:

This patch adds possibility to get tun device's net namespace fd
in the same way we allow to do that for sockets.

Socket ioctl numbers do not intersect with tun-specific, and there
is already SIOCSIFHWADDR used in tun code. So, SIOCGSKNS number
is choosen instead of custom-made for this functionality.

Note, that open_related_ns() uses plain get_net_ns() and it's safe
(net can't be already dead at this moment):

  tun socket is allocated via sk_alloc() with zero last arg (kern = 0).
  So, each alive socket increments net::count, and the socket is definitely
  alive during ioctl syscall.

Also, common variable net is introduced, so small cleanup in TUNSETIFF
is made.

Signed-off-by: Kirill Tkhai <ktkhai@virtuozzo.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
Signed-off-by: Kirill Tkhai <ktkhai@virtuozzo.com>
---
 drivers/net/tun.c |   11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

Patch hide | download patch | download mbox

diff --git a/drivers/net/tun.c b/drivers/net/tun.c
index 8cd39507c64b..9264c06fd7d2 100644
--- a/drivers/net/tun.c
+++ b/drivers/net/tun.c
@@ -70,6 +70,7 @@ 
 #include <net/rtnetlink.h>
 #include <net/sock.h>
 #include <linux/skb_array.h>
+#include <linux/proc_ns.h>
 
 #include <asm/uaccess.h>
 
@@ -2224,7 +2225,7 @@  static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
 	int ret;
 
 	if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || cmd == TUNSETACCTID ||
-			_IOC_TYPE(cmd) == 0x89) {
+	    (_IOC_TYPE(cmd) == 0x89 && cmd != SIOCGSKNS)) {
 		if (copy_from_user(&ifr, argp, ifreq_len))
 			return -EFAULT;
 	} else {
@@ -2276,6 +2277,14 @@  static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
 		tfile->ifindex = ifindex;
 		goto unlock;
 	}
+	if (cmd == SIOCGSKNS) {
+		ret = -EPERM;
+		if (!ns_capable(tfile->net->user_ns, CAP_NET_ADMIN))
+			goto unlock;
+
+		ret = open_net_ns_fd(tfile->net);
+		goto unlock;
+	}
 
 	ret = -EBADFD;
 	if (!tun)