• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2#
3# Copyright 2020 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Namespace related support code."""
18
19import ctypes
20import ctypes.util
21import os
22import socket
23import sys
24
25import net_test
26import sock_diag
27import tcp_test
28
29# //include/linux/fs.h
30MNT_FORCE       = 1         # Attempt to forcibily umount
31MNT_DETACH      = 2         # Just detach from the tree
32MNT_EXPIRE      = 4         # Mark for expiry
33UMOUNT_NOFOLLOW = 8         # Don't follow symlink on umount
34
35# //include/uapi/linux/fs.h
36MS_RDONLY       = 1         # Mount read-only
37MS_NOSUID       = 2         # Ignore suid and sgid bits
38MS_NODEV        = 4         # Disallow access to device special files
39MS_NOEXEC       = 8         # Disallow program execution
40MS_SYNCHRONOUS  = 16        # Writes are synced at once
41MS_REMOUNT      = 32        # Alter flags of a mounted FS
42MS_MANDLOCK     = 64        # Allow mandatory locks on an FS
43MS_DIRSYNC      = 128       # Directory modifications are synchronous
44MS_NOATIME      = 1024      # Do not update access times.
45MS_NODIRATIME   = 2048      # Do not update directory access times
46MS_BIND         = 4096      #
47MS_MOVE         = 8192      #
48MS_REC          = 16384     #
49MS_SILENT       = 32768     #
50MS_POSIXACL     = (1<<16)   # VFS does not apply the umask
51MS_UNBINDABLE   = (1<<17)   # change to unbindable
52MS_PRIVATE      = (1<<18)   # change to private
53MS_SLAVE        = (1<<19)   # change to slave
54MS_SHARED       = (1<<20)   # change to shared
55MS_RELATIME     = (1<<21)   # Update atime relative to mtime/ctime.
56MS_STRICTATIME  = (1<<24)   # Always perform atime updates
57MS_LAZYTIME     = (1<<25)   # Update the on-disk [acm]times lazily
58
59# //include/uapi/linux/sched.h
60CLONE_NEWNS     = 0x00020000   # New mount namespace group
61CLONE_NEWCGROUP = 0x02000000   # New cgroup namespace
62CLONE_NEWUTS    = 0x04000000   # New utsname namespace
63CLONE_NEWIPC    = 0x08000000   # New ipc namespace
64CLONE_NEWUSER   = 0x10000000   # New user namespace
65CLONE_NEWPID    = 0x20000000   # New pid namespace
66CLONE_NEWNET    = 0x40000000   # New network namespace
67
68libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
69
70# See the relevant system call's man pages and:
71#   https://docs.python.org/3/library/ctypes.html#fundamental-data-types
72libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
73                       ctypes.c_ulong, ctypes.c_void_p)
74libc.sethostname.argtype = (ctypes.c_char_p, ctypes.c_size_t)
75libc.umount2.argtypes = (ctypes.c_char_p, ctypes.c_int)
76libc.unshare.argtypes = (ctypes.c_int,)
77
78
79def Mount(src, tgt, fs, flags=MS_NODEV|MS_NOEXEC|MS_NOSUID|MS_RELATIME):
80  ret = libc.mount(src, tgt, fs, flags, None)
81  if ret < 0:
82    errno = ctypes.get_errno()
83    raise OSError(errno, '%s mounting %s on %s (fs=%s flags=0x%x)'
84                  % (os.strerror(errno), src, tgt, fs, flags))
85
86
87def ReMountProc():
88  libc.umount2('/proc', MNT_DETACH)  # Ignore failure: might not be mounted
89  Mount('proc', '/proc', 'proc')
90
91
92def ReMountSys():
93  libc.umount2('/sys', MNT_DETACH)  # Ignore failure: might not be mounted
94  Mount('sysfs', '/sys', 'sysfs')
95
96
97def SetFileContents(f, s):
98  open(f, 'w').write(s)
99
100
101def SetHostname(s):
102  ret = libc.sethostname(s, len(s))
103  if ret < 0:
104    errno = ctypes.get_errno()
105    raise OSError(errno, '%s while sethostname(%s)' % (os.strerror(errno), s))
106
107
108def UnShare(flags):
109  ret = libc.unshare(flags)
110  if ret < 0:
111    errno = ctypes.get_errno()
112    raise OSError(errno, '%s while unshare(0x%x)' % (os.strerror(errno), flags))
113
114
115def DumpMounts(hdr):
116  print('')
117  print(hdr)
118  sys.stdout.write(open('/proc/mounts', 'r').read())
119  print('---')
120
121
122# Requires at least kernel configuration options:
123#   CONFIG_NAMESPACES=y
124#   CONFIG_NET_NS=y
125#   CONFIG_UTS_NS=y
126def IfPossibleEnterNewNetworkNamespace():
127  """Instantiate and transition into a fresh new network namespace if possible."""
128
129  sys.stdout.write('Creating clean namespace... ')
130
131  try:
132    UnShare(CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWNET)
133  except OSError as err:
134    print('failed: %s (likely: no privs or lack of kernel support).' % err)
135    return False
136
137  try:
138    # DumpMounts('Before:')
139    Mount('none', '/', None, MS_REC|MS_PRIVATE)
140    ReMountProc()
141    ReMountSys()
142    # DumpMounts('After:')
143    SetHostname('netns')
144    SetFileContents('/proc/sys/net/ipv4/ping_group_range', '0 2147483647')
145    net_test.SetInterfaceUp('lo')
146  except:
147    print('failed.')
148    # We've already transitioned into the new netns -- it's too late to recover.
149    raise
150
151  print('succeeded.')
152  return True
153
154
155def HasEstablishedTcpSessionOnPort(port):
156  sd = sock_diag.SockDiag()
157
158  sock_id = sd._EmptyInetDiagSockId()
159  sock_id.sport = port
160
161  states = 1 << tcp_test.TCP_ESTABLISHED
162
163  matches = sd.DumpAllInetSockets(socket.IPPROTO_TCP, "",
164                                  sock_id=sock_id, states=states)
165
166  return len(matches) > 0
167