...

Source file src/github.com/opencontainers/runc/libcontainer/standard_init_linux.go

Documentation: github.com/opencontainers/runc/libcontainer

     1  package libcontainer
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"os/exec"
     8  	"strconv"
     9  
    10  	"github.com/opencontainers/runtime-spec/specs-go"
    11  	"github.com/opencontainers/selinux/go-selinux"
    12  	"github.com/sirupsen/logrus"
    13  	"golang.org/x/sys/unix"
    14  
    15  	"github.com/opencontainers/runc/libcontainer/apparmor"
    16  	"github.com/opencontainers/runc/libcontainer/configs"
    17  	"github.com/opencontainers/runc/libcontainer/keys"
    18  	"github.com/opencontainers/runc/libcontainer/seccomp"
    19  	"github.com/opencontainers/runc/libcontainer/system"
    20  	"github.com/opencontainers/runc/libcontainer/utils"
    21  )
    22  
    23  type linuxStandardInit struct {
    24  	pipe          *os.File
    25  	consoleSocket *os.File
    26  	parentPid     int
    27  	fifoFd        int
    28  	logFd         int
    29  	mountFds      []int
    30  	config        *initConfig
    31  }
    32  
    33  func (l *linuxStandardInit) getSessionRingParams() (string, uint32, uint32) {
    34  	var newperms uint32
    35  
    36  	if l.config.Config.Namespaces.Contains(configs.NEWUSER) {
    37  		// With user ns we need 'other' search permissions.
    38  		newperms = 0x8
    39  	} else {
    40  		// Without user ns we need 'UID' search permissions.
    41  		newperms = 0x80000
    42  	}
    43  
    44  	// Create a unique per session container name that we can join in setns;
    45  	// However, other containers can also join it.
    46  	return "_ses." + l.config.ContainerId, 0xffffffff, newperms
    47  }
    48  
    49  func (l *linuxStandardInit) Init() error {
    50  	if !l.config.Config.NoNewKeyring {
    51  		if err := selinux.SetKeyLabel(l.config.ProcessLabel); err != nil {
    52  			return err
    53  		}
    54  		defer selinux.SetKeyLabel("") //nolint: errcheck
    55  		ringname, keepperms, newperms := l.getSessionRingParams()
    56  
    57  		// Do not inherit the parent's session keyring.
    58  		if sessKeyId, err := keys.JoinSessionKeyring(ringname); err != nil {
    59  			// If keyrings aren't supported then it is likely we are on an
    60  			// older kernel (or inside an LXC container). While we could bail,
    61  			// the security feature we are using here is best-effort (it only
    62  			// really provides marginal protection since VFS credentials are
    63  			// the only significant protection of keyrings).
    64  			//
    65  			// TODO(cyphar): Log this so people know what's going on, once we
    66  			//               have proper logging in 'runc init'.
    67  			if !errors.Is(err, unix.ENOSYS) {
    68  				return fmt.Errorf("unable to join session keyring: %w", err)
    69  			}
    70  		} else {
    71  			// Make session keyring searchable. If we've gotten this far we
    72  			// bail on any error -- we don't want to have a keyring with bad
    73  			// permissions.
    74  			if err := keys.ModKeyringPerm(sessKeyId, keepperms, newperms); err != nil {
    75  				return fmt.Errorf("unable to mod keyring permissions: %w", err)
    76  			}
    77  		}
    78  	}
    79  
    80  	if err := setupNetwork(l.config); err != nil {
    81  		return err
    82  	}
    83  	if err := setupRoute(l.config.Config); err != nil {
    84  		return err
    85  	}
    86  
    87  	// initialises the labeling system
    88  	selinux.GetEnabled()
    89  
    90  	// We don't need the mountFds after prepareRootfs() nor if it fails.
    91  	err := prepareRootfs(l.pipe, l.config, l.mountFds)
    92  	for _, m := range l.mountFds {
    93  		if m == -1 {
    94  			continue
    95  		}
    96  
    97  		if err := unix.Close(m); err != nil {
    98  			return fmt.Errorf("Unable to close mountFds fds: %w", err)
    99  		}
   100  	}
   101  
   102  	if err != nil {
   103  		return err
   104  	}
   105  
   106  	// Set up the console. This has to be done *before* we finalize the rootfs,
   107  	// but *after* we've given the user the chance to set up all of the mounts
   108  	// they wanted.
   109  	if l.config.CreateConsole {
   110  		if err := setupConsole(l.consoleSocket, l.config, true); err != nil {
   111  			return err
   112  		}
   113  		if err := system.Setctty(); err != nil {
   114  			return &os.SyscallError{Syscall: "ioctl(setctty)", Err: err}
   115  		}
   116  	}
   117  
   118  	// Finish the rootfs setup.
   119  	if l.config.Config.Namespaces.Contains(configs.NEWNS) {
   120  		if err := finalizeRootfs(l.config.Config); err != nil {
   121  			return err
   122  		}
   123  	}
   124  
   125  	if hostname := l.config.Config.Hostname; hostname != "" {
   126  		if err := unix.Sethostname([]byte(hostname)); err != nil {
   127  			return &os.SyscallError{Syscall: "sethostname", Err: err}
   128  		}
   129  	}
   130  	if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil {
   131  		return fmt.Errorf("unable to apply apparmor profile: %w", err)
   132  	}
   133  
   134  	for key, value := range l.config.Config.Sysctl {
   135  		if err := writeSystemProperty(key, value); err != nil {
   136  			return err
   137  		}
   138  	}
   139  	for _, path := range l.config.Config.ReadonlyPaths {
   140  		if err := readonlyPath(path); err != nil {
   141  			return fmt.Errorf("can't make %q read-only: %w", path, err)
   142  		}
   143  	}
   144  	for _, path := range l.config.Config.MaskPaths {
   145  		if err := maskPath(path, l.config.Config.MountLabel); err != nil {
   146  			return fmt.Errorf("can't mask path %s: %w", path, err)
   147  		}
   148  	}
   149  	pdeath, err := system.GetParentDeathSignal()
   150  	if err != nil {
   151  		return fmt.Errorf("can't get pdeath signal: %w", err)
   152  	}
   153  	if l.config.NoNewPrivileges {
   154  		if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
   155  			return &os.SyscallError{Syscall: "prctl(SET_NO_NEW_PRIVS)", Err: err}
   156  		}
   157  	}
   158  	// Tell our parent that we're ready to Execv. This must be done before the
   159  	// Seccomp rules have been applied, because we need to be able to read and
   160  	// write to a socket.
   161  	if err := syncParentReady(l.pipe); err != nil {
   162  		return fmt.Errorf("sync ready: %w", err)
   163  	}
   164  	if err := selinux.SetExecLabel(l.config.ProcessLabel); err != nil {
   165  		return fmt.Errorf("can't set process label: %w", err)
   166  	}
   167  	defer selinux.SetExecLabel("") //nolint: errcheck
   168  	// Without NoNewPrivileges seccomp is a privileged operation, so we need to
   169  	// do this before dropping capabilities; otherwise do it as late as possible
   170  	// just before execve so as few syscalls take place after it as possible.
   171  	if l.config.Config.Seccomp != nil && !l.config.NoNewPrivileges {
   172  		seccompFd, err := seccomp.InitSeccomp(l.config.Config.Seccomp)
   173  		if err != nil {
   174  			return err
   175  		}
   176  
   177  		if err := syncParentSeccomp(l.pipe, seccompFd); err != nil {
   178  			return err
   179  		}
   180  	}
   181  	if err := finalizeNamespace(l.config); err != nil {
   182  		return err
   183  	}
   184  	// finalizeNamespace can change user/group which clears the parent death
   185  	// signal, so we restore it here.
   186  	if err := pdeath.Restore(); err != nil {
   187  		return fmt.Errorf("can't restore pdeath signal: %w", err)
   188  	}
   189  	// Compare the parent from the initial start of the init process and make
   190  	// sure that it did not change.  if the parent changes that means it died
   191  	// and we were reparented to something else so we should just kill ourself
   192  	// and not cause problems for someone else.
   193  	if unix.Getppid() != l.parentPid {
   194  		return unix.Kill(unix.Getpid(), unix.SIGKILL)
   195  	}
   196  	// Check for the arg before waiting to make sure it exists and it is
   197  	// returned as a create time error.
   198  	name, err := exec.LookPath(l.config.Args[0])
   199  	if err != nil {
   200  		return err
   201  	}
   202  	// exec.LookPath in Go < 1.20 might return no error for an executable
   203  	// residing on a file system mounted with noexec flag, so perform this
   204  	// extra check now while we can still return a proper error.
   205  	// TODO: remove this once go < 1.20 is not supported.
   206  	if err := eaccess(name); err != nil {
   207  		return &os.PathError{Op: "eaccess", Path: name, Err: err}
   208  	}
   209  
   210  	// Set seccomp as close to execve as possible, so as few syscalls take
   211  	// place afterward (reducing the amount of syscalls that users need to
   212  	// enable in their seccomp profiles). However, this needs to be done
   213  	// before closing the pipe since we need it to pass the seccompFd to
   214  	// the parent.
   215  	if l.config.Config.Seccomp != nil && l.config.NoNewPrivileges {
   216  		seccompFd, err := seccomp.InitSeccomp(l.config.Config.Seccomp)
   217  		if err != nil {
   218  			return fmt.Errorf("unable to init seccomp: %w", err)
   219  		}
   220  
   221  		if err := syncParentSeccomp(l.pipe, seccompFd); err != nil {
   222  			return err
   223  		}
   224  	}
   225  	// Close the pipe to signal that we have completed our init.
   226  	logrus.Debugf("init: closing the pipe to signal completion")
   227  	_ = l.pipe.Close()
   228  
   229  	// Close the log pipe fd so the parent's ForwardLogs can exit.
   230  	if err := unix.Close(l.logFd); err != nil {
   231  		return &os.PathError{Op: "close log pipe", Path: "fd " + strconv.Itoa(l.logFd), Err: err}
   232  	}
   233  
   234  	// Wait for the FIFO to be opened on the other side before exec-ing the
   235  	// user process. We open it through /proc/self/fd/$fd, because the fd that
   236  	// was given to us was an O_PATH fd to the fifo itself. Linux allows us to
   237  	// re-open an O_PATH fd through /proc.
   238  	fifoPath := "/proc/self/fd/" + strconv.Itoa(l.fifoFd)
   239  	fd, err := unix.Open(fifoPath, unix.O_WRONLY|unix.O_CLOEXEC, 0)
   240  	if err != nil {
   241  		return &os.PathError{Op: "open exec fifo", Path: fifoPath, Err: err}
   242  	}
   243  	if _, err := unix.Write(fd, []byte("0")); err != nil {
   244  		return &os.PathError{Op: "write exec fifo", Path: fifoPath, Err: err}
   245  	}
   246  
   247  	// Close the O_PATH fifofd fd before exec because the kernel resets
   248  	// dumpable in the wrong order. This has been fixed in newer kernels, but
   249  	// we keep this to ensure CVE-2016-9962 doesn't re-emerge on older kernels.
   250  	// N.B. the core issue itself (passing dirfds to the host filesystem) has
   251  	// since been resolved.
   252  	// https://github.com/torvalds/linux/blob/v4.9/fs/exec.c#L1290-L1318
   253  	_ = unix.Close(l.fifoFd)
   254  
   255  	s := l.config.SpecState
   256  	s.Pid = unix.Getpid()
   257  	s.Status = specs.StateCreated
   258  	if err := l.config.Config.Hooks[configs.StartContainer].RunHooks(s); err != nil {
   259  		return err
   260  	}
   261  
   262  	// Close all file descriptors we are not passing to the container. This is
   263  	// necessary because the execve target could use internal runc fds as the
   264  	// execve path, potentially giving access to binary files from the host
   265  	// (which can then be opened by container processes, leading to container
   266  	// escapes). Note that because this operation will close any open file
   267  	// descriptors that are referenced by (*os.File) handles from underneath
   268  	// the Go runtime, we must not do any file operations after this point
   269  	// (otherwise the (*os.File) finaliser could close the wrong file). See
   270  	// CVE-2024-21626 for more information as to why this protection is
   271  	// necessary.
   272  	//
   273  	// This is not needed for runc-dmz, because the extra execve(2) step means
   274  	// that all O_CLOEXEC file descriptors have already been closed and thus
   275  	// the second execve(2) from runc-dmz cannot access internal file
   276  	// descriptors from runc.
   277  	if err := utils.UnsafeCloseFrom(l.config.PassedFilesCount + 3); err != nil {
   278  		return err
   279  	}
   280  	return system.Exec(name, l.config.Args[0:], os.Environ())
   281  }
   282  

View as plain text