[PATCH v3 5/6] net: namespace: allow setting NSIDs outside current namespace

From: Jonas Bonn
Date: Thu Nov 07 2019 - 08:28:20 EST


Currently it is only possible to move an interface to a new namespace if
the destination namespace has an ID in the interface's current namespace.
If the interface already resides outside of the current namespace, then
we may need to assign the destination namespace an ID in the interface's
namespace in order to effect the move.

This patch allows namespace ID's to be created outside of the current
namespace. With this, the following is possible:

i) Our namespace is 'A'.
ii) The interface resides in namespace 'B'
iii) We can assign an ID for NS 'A' in NS 'B'
iv) We can then move the interface into our own namespace.

and

i) Our namespace is 'A'; namespaces 'B' and 'C' also exist
ii) We can assign an ID for namespace 'C' in namespace 'B'
iii) We can then create a VETH interface directly in namespace 'B' with
the other end in 'C', all without ever leaving namespace 'A'

Signed-off-by: Jonas Bonn <jonas@xxxxxxxxxxx>
Acked-by: Nicolas Dichtel <nicolas.dichtel@xxxxxxxxx>
---
net/core/net_namespace.c | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)

diff --git a/net/core/net_namespace.c b/net/core/net_namespace.c
index 39402840025e..ebb01903d1f7 100644
--- a/net/core/net_namespace.c
+++ b/net/core/net_namespace.c
@@ -726,6 +726,7 @@ static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr *tb[NETNSA_MAX + 1];
struct nlattr *nla;
struct net *peer;
+ struct net *target = NULL;
int nsid, err;

err = nlmsg_parse_deprecated(nlh, sizeof(struct rtgenmsg), tb,
@@ -754,6 +755,21 @@ static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh,
return PTR_ERR(peer);
}

+ if (tb[NETNSA_TARGET_NSID]) {
+ int id = nla_get_s32(tb[NETNSA_TARGET_NSID]);
+
+ target = rtnl_get_net_ns_capable(NETLINK_CB(skb).sk, id);
+ if (IS_ERR(target)) {
+ NL_SET_BAD_ATTR(extack, tb[NETNSA_TARGET_NSID]);
+ NL_SET_ERR_MSG(extack,
+ "Target netns reference is invalid");
+ err = PTR_ERR(target);
+ goto out;
+ }
+
+ net = target;
+ }
+
spin_lock_bh(&net->nsid_lock);
if (__peernet2id(net, peer) >= 0) {
spin_unlock_bh(&net->nsid_lock);
@@ -775,6 +791,9 @@ static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh,
NL_SET_BAD_ATTR(extack, tb[NETNSA_NSID]);
NL_SET_ERR_MSG(extack, "The specified nsid is already used");
}
+
+ if (target)
+ put_net(target);
out:
put_net(peer);
return err;
--
2.20.1