Match VT device paths to be blocked from mounting exactly

As @mheon pointed out in PR #17055[^1], isVirtualConsoleDevice() does
not only matches VT device paths but also devices named like
/dev/tty0abcd.
This causes that non VT device paths named /dev/tty[0-9]+[A-Za-z]+ are
not mounted into privileged container and systemd containers accidentally.

This is an unlikely issue because the Linux kernel does not use device
paths like that.
To make it failproof and prevent issues in unlikely scenarios, change
isVirtualConsoleDevice() to exactly match ^/dev/tty[0-9]+$ paths.

Because it is not possible to match this path exactly with Glob syntax,
the path is now checked with strings.TrimPrefix() and
strconv.ParseUint().
ParseUint uses a bitsize of 16, this is sufficient because the max
number of TTY devices is 512 in Linux 6.1.5.
(Checked via 'git grep -e '#define' --and -e 'TTY_MINORS').

The commit also adds a unit-test for isVirtualConsoleDevice().

Fixes: f4c81b0aa5fd ("Only prevent VTs to be mounted inside...")

[^1]: https://github.com/containers/podman/pull/17055#issuecomment-1378904068

Signed-off-by: Fabian Holler <mail@fholler.de>
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
This commit is contained in:
Fabian Holler
2023-01-18 09:13:50 +01:00
committed by Daniel J Walsh
parent 986a3a61a8
commit b0b166b5bb
2 changed files with 68 additions and 10 deletions

View File

@ -5,8 +5,9 @@ import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"syscall"
"github.com/containers/podman/v4/libpod/define"
@ -70,20 +71,23 @@ func FindDeviceNodes() (map[string]string, error) {
return nodes, nil
}
func isVirtualConsoleDevice(device string) bool {
// isVirtualConsoleDevice returns true if path is a virtual console device
// (/dev/tty\d+).
// The passed path must be clean (filepath.Clean).
func isVirtualConsoleDevice(path 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
suffix := strings.TrimPrefix(path, "/dev/tty")
if suffix == path || suffix == "" {
return false
}
// 16bit because, max. supported TTY devices is 512 in Linux 6.1.5.
_, err := strconv.ParseUint(suffix, 10, 16)
return err == nil
}
func AddPrivilegedDevices(g *generate.Generator, systemdMode bool) error {