Only prevent VTs to be mounted inside privileged systemd containers

While mounting virtual console devices in a systemd container is a
recipe for disaster (I experienced it first hand), mounting serial
console devices, modems, and others should still be done by default
for privileged systemd-based containers.

v2, addressing the review from @fho:
 - use backticks in the regular expression to remove backslashes
 - pre-compile the regex at the package level
 - drop IsVirtualTerminalDevice (not needed for a one-liner)

v3, addressing the review from @fho and @rhatdan:
 - re-introduce a private function for matching the device names
 - use path.Match rather than a regex not to slow down startup time

Closes #16925.

Fixes: 5a2405ae1b3a ("Don't mount /dev/tty* inside privileged...")
Signed-off-by: Martin Roukala (né Peres) <martin.roukala@mupuf.org>
This commit is contained in:
Martin Roukala (né Peres)
2023-01-10 12:10:13 +02:00
parent 382c55eeaa
commit f4c81b0aa5
2 changed files with 47 additions and 7 deletions

View File

@ -5,6 +5,7 @@ import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"syscall"
@ -70,6 +71,22 @@ func FindDeviceNodes() (map[string]string, error) {
return nodes, nil
}
func isVirtualConsoleDevice(device string) bool {
/*
Virtual consoles are of the form `/dev/tty\d+`, any other device such as
/dev/tty, ttyUSB0, or ttyACM0 should not be matched.
See `man 4 console` for more information.
NOTE: Matching is done using path.Match even though a regular expression
would have been more accurate. This is because a regular
expression would have required pre-compilation, which would have
increase the startup time needlessly or made the code more complex
than needed.
*/
matched, _ := path.Match("/dev/tty[0-9]*", device)
return matched
}
func AddPrivilegedDevices(g *generate.Generator, systemdMode bool) error {
hostDevices, err := getDevices("/dev")
if err != nil {
@ -104,7 +121,7 @@ func AddPrivilegedDevices(g *generate.Generator, systemdMode bool) error {
}
} else {
for _, d := range hostDevices {
if systemdMode && strings.HasPrefix(d.Path, "/dev/tty") {
if systemdMode && isVirtualConsoleDevice(d.Path) {
continue
}
g.AddDevice(d)