From nobody Fri Oct 3 07:39:19 2025 Received: from mail-pj1-f48.google.com (mail-pj1-f48.google.com [209.85.216.48]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CE62428727E; Wed, 3 Sep 2025 15:50:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1756914610; cv=none; b=K2UQVIwWr3uxS5vUv+/M0o76A3k2BjNP8VeklqnlD+XD+fPdZhft2tIVJsmPOETU29v+ORIIshe6PJdjdrFRHfalXxJhprtb1LLSq9DeIx6guPoJefdhChg2THNOY34Pcj/noxcxH+Bv7iKQcu7AJeTTbQY9JGj3FeAa6WrIQCg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1756914610; c=relaxed/simple; bh=ACGLVoa1ITk0Ez+JYQFPAnmmmqhw+pfnrdOInKeVFnk=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:To:Cc; b=AEQJFhmExw46arjIDk4Ysf/OLWNpb0w/Y1bBLKkW8yMAPXYV+WLwa2x3+kts/xlYojBvcN2MXaXhc9L7Tzo1xv5Nuja0K2S4apR6sKgnqtNdguLeVgT4SUg+wVDxOGNDtTeyUgbjA1u/nI0ox1MvRApGL28bmG2879XOF8hJBqo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=fQMVTTf1; arc=none smtp.client-ip=209.85.216.48 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="fQMVTTf1" Received: by mail-pj1-f48.google.com with SMTP id 98e67ed59e1d1-32b5d3e1762so979982a91.3; Wed, 03 Sep 2025 08:50:05 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1756914605; x=1757519405; darn=vger.kernel.org; h=cc:to:message-id:content-transfer-encoding:mime-version:subject :date:from:from:to:cc:subject:date:message-id:reply-to; bh=mrVTTRKDgBpM21zv3SMBV/FlS761AOyx2YN9Dh3TAkA=; b=fQMVTTf1BFhy+ZXb5y+McT2bqGMJY3vI1Yz1soN86M7Dj4pP2YGP5Hj5VjB8o+n3em MevaRBYZLd4MSx93NDNxCiuAds5P35feRbtmThh9OkDG0bfjaCrIHiq3h+i7ZVy2Fz1y 3a7clooKIEeFLm+khepH664XO2nNuLyMvMVSquJw6Wcx5sN3WBpGuSmbiA8FEBTqTxb1 nNQ0v8SasegkL0ceLlUyhjb5m7BMoQ/4bKJ2kkW1EjifnmGr1DVOELFYkKqX1C2r5ubE bam5wfAws905+NucQBmUeMmHzlYXboBfExdjtcYTdLNY8TPC6ncvn6yfzX01xu14V7LE GBcA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1756914605; x=1757519405; h=cc:to:message-id:content-transfer-encoding:mime-version:subject :date:from:x-gm-message-state:from:to:cc:subject:date:message-id :reply-to; bh=mrVTTRKDgBpM21zv3SMBV/FlS761AOyx2YN9Dh3TAkA=; b=Kpc/GK8H3z+Zo/+3KsrO5MhO2Y8xrCoFw6EYl4CsurfF3cxj9WAi0Rl50fFh/Tk1M/ PdOEk0khz+7OekElWO+oHHPcMaHs2CDIkqnO4F0sf+eQBlpJPtqZGzWlWoR753tZuAAA CQq2i+XJlCdXtVFJ70Q3Y3MNZyctbxmF4R+BhblndsPXntx+rpK0+mypmYj8/Vs+6nje xrCROCNAGO4K8PqGHJGWqpDvAJgFSABs6smnSS+1n6lIXBDtU0APaVBhbV1UhwUimGzV BsSGJaTP0EX4kzgw4/S+4bLVspQQKXBgAFQFAPx6ZjCuNoN2A91SqdYk8goIZWJG7z3l Ro5A== X-Forwarded-Encrypted: i=1; AJvYcCVmlGHWi1OLA9FRUO892em7WXZnKV+rm6krkL3Bdhf81xaarLoJ0+CdkurqGOd218NYDLlAboRu/kdvRIP9cjs=@vger.kernel.org, AJvYcCWJwDbr4yLi1NDN7uF1OkF9nKWWo2i/aiQiwYwhCdGcrPPrs84oHkPaoerWwm7BD7KpT2sbzMacN+Ac2MPxclz7@vger.kernel.org, AJvYcCWLnY2TaobpqdBsnhi4xpXmru8ITl/ws2FHFI4HYUBCx/Ts17WNECH7dVlG/HhC8aeW29LZ6WxwuYqp1hnm@vger.kernel.org X-Gm-Message-State: AOJu0YxbYlKWLpoMbosb4OhITSCI7x7d6cLMMJSZmw0R3vsxCqxEjS3k J/W6qQfij7S3vygTyfhRDsuIEUmt0Clhayi/ZI6hHtb6gpGaRERwaqqkK0KMeWDx X-Gm-Gg: ASbGncvMmFsig77Z5AnBFwMi9UgMBkMPuAyJwKQJExOyx9CpPI1mS1B+ocJfJ+NjvRj cEz/ljwXpshHO9UO8hXWtAaK+8wZB2TU9R/ccx1m3jQKppAY4TvFEktrZGD6/qTM7X64rUgwTo2 Se7czFWlawpjTWc9XA5S+lEWEmmIdv7sQDKZwYKQhp28748p19Axn4outqzEPxU1cuKIBFTOL/E yk7KenvznxdT/qD8f2BDb/WOl0mO4LDq6+qstMV0DyDqZZdRScyrd4fzujYojSGxaM+LO3vW5Il +Y4eEhX1+2Wnp6dn6GbQUh8ZZ1zzs4eGV7pxZw77gcuFwJk9pKPdga9SK96vRVwLcVs4aY5C6Sy m9Iv6/zF9PwML9tYFsbBrCZB568ZWVIE= X-Google-Smtp-Source: AGHT+IEjb3PuRG1+A3y2k4QmtmY0YrX/NJfPE219Et7+qIMvlyd6uaRYHb7+OE97eBv7hwbe3TOlxA== X-Received: by 2002:a17:90b:2890:b0:32b:5d0f:2184 with SMTP id 98e67ed59e1d1-32b5d1e6c31mr4425365a91.26.1756914604293; Wed, 03 Sep 2025 08:50:04 -0700 (PDT) Received: from [0.0.5.57] ([136.159.213.138]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-329e9fd022dsm5249059a91.3.2025.09.03.08.50.03 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 03 Sep 2025 08:50:03 -0700 (PDT) From: Abhinav Saxena Date: Wed, 03 Sep 2025 09:49:43 -0600 Subject: [PATCH RESEND v4] selftests/tty: add TIOCSTI test suite Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250903-toicsti-bug-v4-1-4894b6649ef8@gmail.com> X-B4-Tracking: v=1; b=H4sIAJZjuGgC/2XOPU/DMBAG4L9SecbIvnNiuxMDXRlgRAz+uKSWa IPiEIGq/HfcgNQkjHen533vwjL1iTLb7y6spzHl1J3LoO52LBzduSWeYpkZCKhELQ0fuhTykLj /bLk2AN6QVQ6BFfHRU5O+5rRX9nx4OTw9sreyP6Y8dP33XDLK+fqXZ1d5o+SCk4Cg0VWVD/GhP bn0fh+60zX+1wD8Nw1qhRq9UB4W5to9wq1PS1xb4JJ7aVAbTeTAbi0uLIq1xWJjhOiC1Q1ot7X qZq3Y/KyKpSrYWpDwGOulnabpB5smq+WWAQAA X-Change-ID: 20250618-toicsti-bug-7822b8e94a32 To: Shuah Khan , Nathan Chancellor , Nick Desaulniers , Bill Wendling , Justin Stitt , Paul Moore , Kees Cook , Greg Kroah-Hartman , Jiri Slaby Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, llvm@lists.linux.dev, linux-hardening@vger.kernel.org, linux-serial@vger.kernel.org, Abhinav Saxena X-Mailer: b4 0.14.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1756914603; l=24411; i=xandfury@gmail.com; s=20250614; h=from:subject:message-id; bh=ACGLVoa1ITk0Ez+JYQFPAnmmmqhw+pfnrdOInKeVFnk=; b=royLYGS16or+sT2Bwi5yfqxGGRMoa4cxmbXj8MQHn7WlA/Y6MNUzIxf3GvYl7T6pXWVn6oS0r acC3xdss1VtCGaxYXnQ9hXszoPH6775xZK1MQxYlsYcSG+8p4n0pL6Z X-Developer-Key: i=xandfury@gmail.com; a=ed25519; pk=YN6w7WNet8skqvMWxhG5BlAmtd1SQmo8If6Mofh4k44= TIOCSTI is a TTY ioctl command that allows inserting characters into the terminal input queue, making it appear as if the user typed those characters. This functionality has behavior that varies based on system configuration and process credentials. The dev.tty.legacy_tiocsti sysctl introduced in commit 83efeeeb3d04 ("tty: Allow TIOCSTI to be disabled") controls TIOCSTI usage. When disabled, TIOCSTI requires CAP_SYS_ADMIN capability. The current implementation checks the current process's credentials via capable(CAP_SYS_ADMIN), but does not validate against the file opener's credentials stored in file->f_cred. This creates different behavior when file descriptors are passed between processes via SCM_RIGHTS. Add a test suite with 16 test variants using fixture variants to verify TIOCSTI behavior when dev.tty.legacy_tiocsti is enabled/disabled: - Basic TIOCSTI tests (8 variants): Direct testing with different capability and controlling terminal combinations - FD passing tests (8 variants): Test behavior when file descriptors are passed between processes with different capabilities The FD passing tests document this behavior - some tests show different results than expected based on file opener credentials, demonstrating that TIOCSTI uses current process credentials rather than file opener credentials. The tests validate proper enforcement of the legacy_tiocsti sysctl. Test implementation uses openpty(3) with TIOCSCTTY for isolated PTY environments. See tty_ioctl(4) for details on TIOCSTI behavior and security requirements. Signed-off-by: Abhinav Saxena --- RESEND: add TTY/serial maintainers and linux-serial CCs. No code changes. - Link to orignal v4: https://lore.kernel.org/r/20250902-toicsti-bug-v4-1-e= 5c960e0b3d6@gmail.com Changes in v4: - Moved skip conditions and sysctl setup from TEST_F to FIXTURE_SETUP (Kees= Cook) - Fixed fclose() error handling in set_legacy_tiocsti_setting (Kees Cook) - Extracted run_basic_tiocsti_test() and run_fdpass_tiocsti_test functions = (Kees Cook) - Removed redundant sysctl restore logic from TEST_F (Kees Cook) - Simplified FIXTURE_TEARDOWN (Kees Cook) - Replace drop_to_nobody() to drop_all_privs() which should be more portabl= e (Justin Stitt) - Link to v3: https://lore.kernel.org/r/20250730-toicsti-bug-v3-1-dd2dac97f= 27a@gmail.com Add selftests for TIOCSTI ioctl To run all tests: $ sudo ./tools/testing/selftests/tty/tty_tiocsti_test Test Results: - PASSED: 13/16 tests - Different behavior: 3/16 tests (documenting credential checking behavior) All tests validated using: - scripts/checkpatch.pl --strict (clean output) - Functional testing on kernel v6.16-rc2 Changes in v3: - Replaced all printf() calls with TH_LOG() for proper test logging (Kees C= ook) - Added struct __test_metadata parameter to helper functions - Moved common legacy_tiocsti availability check to FIXTURE_SETUP() - Implemented sysctl modification/restoration in FIXTURE_SETUP/TEARDOWN - Used openpty() with TIOCSCTTY for reliable PTY testing environment - Fixed child/parent synchronization in FD passing tests - Replaced manual _exit(1) handling with proper ASSERT statements - Switched // comments to /* */ format throughout - Expanded to 16 test variants using fixture variants - Enhanced error handling and test reliability - Link to v2: https://lore.kernel.org/r/20250713-toicsti-bug-v2-1-b183787ee= a29@gmail.com - Link to v1: https://lore.kernel.org/r/20250622-toicsti-bug-v1-0-f374373b0= 4b2@gmail.com References: - tty_ioctl(4) - documents TIOCSTI ioctl and capability requirements - openpty(3) - pseudo-terminal creation and management - commit 83efeeeb3d04 ("tty: Allow TIOCSTI to be disabled") - Documentation/security/credentials.rst - https://github.com/KSPP/linux/issues/156 - https://lore.kernel.org/linux-hardening/Y0m9l52AKmw6Yxi1@hostpad/ - drivers/tty/Kconfig - Documentation/driver-api/tty/ --- tools/testing/selftests/tty/Makefile | 6 +- tools/testing/selftests/tty/config | 1 + tools/testing/selftests/tty/tty_tiocsti_test.c | 650 +++++++++++++++++++++= ++++ 3 files changed, 656 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/tty/Makefile b/tools/testing/selftests= /tty/Makefile index 50d7027b2ae3fb495dd1c0684363fa8f426be42c..7f6fbe5a0cd5663310e334d9d06= 8b21dab9136ec 100644 --- a/tools/testing/selftests/tty/Makefile +++ b/tools/testing/selftests/tty/Makefile @@ -1,5 +1,9 @@ # SPDX-License-Identifier: GPL-2.0 CFLAGS =3D -O2 -Wall -TEST_GEN_PROGS :=3D tty_tstamp_update +TEST_GEN_PROGS :=3D tty_tstamp_update tty_tiocsti_test +LDLIBS +=3D -lcap =20 include ../lib.mk + +# Add libcap for TIOCSTI test +$(OUTPUT)/tty_tiocsti_test: LDLIBS +=3D -lcap diff --git a/tools/testing/selftests/tty/config b/tools/testing/selftests/t= ty/config new file mode 100644 index 0000000000000000000000000000000000000000..c6373aba66366c82435bb26c019= eb360eb6310eb --- /dev/null +++ b/tools/testing/selftests/tty/config @@ -0,0 +1 @@ +CONFIG_LEGACY_TIOCSTI=3Dy diff --git a/tools/testing/selftests/tty/tty_tiocsti_test.c b/tools/testing= /selftests/tty/tty_tiocsti_test.c new file mode 100644 index 0000000000000000000000000000000000000000..5e767e6cb3ef8f05c5430eb0fcc= 792064c446c03 --- /dev/null +++ b/tools/testing/selftests/tty/tty_tiocsti_test.c @@ -0,0 +1,650 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * TTY Tests - TIOCSTI + * + * Copyright =C2=A9 2025 Abhinav Saxena + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../kselftest_harness.h" + +enum test_type { + TEST_PTY_TIOCSTI_BASIC, + TEST_PTY_TIOCSTI_FD_PASSING, + /* other tests cases such as serial may be added. */ +}; + +/* + * Test Strategy: + * - Basic tests: Use PTY with/without TIOCSCTTY (controlling terminal for + * current process) + * - FD passing tests: Child creates PTY, parent receives FD (demonstrates + * security issue) + * + * SECURITY VULNERABILITY DEMONSTRATION: + * FD passing tests show that TIOCSTI uses CURRENT process credentials, not + * opener credentials. This means privileged processes can be given FDs fr= om + * unprivileged processes and successfully perform TIOCSTI operations that= the + * unprivileged process couldn't do directly. + * + * Attack scenario: + * 1. Unprivileged process opens TTY (direct TIOCSTI fails due to lack of + * privileges) + * 2. Unprivileged process passes FD to privileged process via SCM_RIGHTS + * 3. Privileged process can use TIOCSTI on the FD (succeeds due to its + * privileges) + * 4. Result: Effective privilege escalation via file descriptor passing + * + * This matches the kernel logic in tiocsti(): + * 1. if (!tty_legacy_tiocsti && !capable(CAP_SYS_ADMIN)) return -EIO; + * 2. if ((current->signal->tty !=3D tty) && !capable(CAP_SYS_ADMIN)) + * return -EPERM; + * Note: Both checks use capable() on CURRENT process, not FD opener! + * + * If the file credentials were also checked along with the capable() chec= ks + * then the results for FD pass tests would be consistent with the basic t= ests. + */ + +FIXTURE(tiocsti) +{ + int pty_master_fd; /* PTY - for basic tests */ + int pty_slave_fd; + bool has_pty; + bool initial_cap_sys_admin; + int original_legacy_tiocsti_setting; + bool can_modify_sysctl; +}; + +FIXTURE_VARIANT(tiocsti) +{ + const enum test_type test_type; + const bool controlling_tty; /* true=3Dcurrent->signal->tty =3D=3D tty */ + const int legacy_tiocsti; /* 0=3Drestricted, 1=3Dpermissive */ + const bool requires_cap; /* true=3Dwith CAP_SYS_ADMIN, false=3Dwithout */ + const int expected_success; /* 0=3Dsuccess, -EIO/-EPERM=3Dspecific error = */ +}; + +/* + * Tests Controlling Terminal Variants (current->signal->tty =3D=3D tty) + * + * TIOCSTI Test Matrix: + * + * | legacy_tiocsti | CAP_SYS_ADMIN | Expected Result | Error | + * |----------------|---------------|-----------------|-------| + * | 1 (permissive) | true | SUCCESS | - | + * | 1 (permissive) | false | SUCCESS | - | + * | 0 (restricted) | true | SUCCESS | - | + * | 0 (restricted) | false | FAILURE | -EIO | + */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(tiocsti, basic_pty_permissive_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D true, + .legacy_tiocsti =3D 1, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_pty_permissive_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D true, + .legacy_tiocsti =3D 1, + .requires_cap =3D false, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_pty_restricted_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D true, + .legacy_tiocsti =3D 0, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_pty_restricted_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D true, + .legacy_tiocsti =3D 0, + .requires_cap =3D false, + .expected_success =3D -EIO, /* FAILURE: legacy restriction */ +}; /* clang-format on */ + +/* + * Note for FD Passing Test Variants + * Since we're testing the scenario where an unprivileged process pass an = FD + * to a privileged one, .requires_cap here means the caps of the child pro= cess. + * Not the parent; parent would always be privileged. + */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(tiocsti, fdpass_pty_permissive_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D true, + .legacy_tiocsti =3D 1, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_pty_permissive_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D true, + .legacy_tiocsti =3D 1, + .requires_cap =3D false, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_pty_restricted_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D true, + .legacy_tiocsti =3D 0, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_pty_restricted_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D true, + .legacy_tiocsti =3D 0, + .requires_cap =3D false, + .expected_success =3D -EIO, +}; /* clang-format on */ + +/* + * Non-Controlling Terminal Variants (current->signal->tty !=3D tty) + * + * TIOCSTI Test Matrix: + * + * | legacy_tiocsti | CAP_SYS_ADMIN | Expected Result | Error | + * |----------------|---------------|-----------------|-------| + * | 1 (permissive) | true | SUCCESS | - | + * | 1 (permissive) | false | FAILURE | -EPERM| + * | 0 (restricted) | true | SUCCESS | - | + * | 0 (restricted) | false | FAILURE | -EIO | + */ + +/* clang-format off */ +FIXTURE_VARIANT_ADD(tiocsti, basic_nopty_permissive_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D false, + .legacy_tiocsti =3D 1, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_nopty_permissive_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D false, + .legacy_tiocsti =3D 1, + .requires_cap =3D false, + .expected_success =3D -EPERM, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_nopty_restricted_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D false, + .legacy_tiocsti =3D 0, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, basic_nopty_restricted_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_BASIC, + .controlling_tty =3D false, + .legacy_tiocsti =3D 0, + .requires_cap =3D false, + .expected_success =3D -EIO, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_nopty_permissive_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D false, + .legacy_tiocsti =3D 1, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_nopty_permissive_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D false, + .legacy_tiocsti =3D 1, + .requires_cap =3D false, + .expected_success =3D -EPERM, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_nopty_restricted_withcap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D false, + .legacy_tiocsti =3D 0, + .requires_cap =3D true, + .expected_success =3D 0, +}; + +FIXTURE_VARIANT_ADD(tiocsti, fdpass_nopty_restricted_nocap) { + .test_type =3D TEST_PTY_TIOCSTI_FD_PASSING, + .controlling_tty =3D false, + .legacy_tiocsti =3D 0, + .requires_cap =3D false, + .expected_success =3D -EIO, +}; /* clang-format on */ + +/* Helper function to send FD via SCM_RIGHTS */ +static int send_fd_via_socket(int socket_fd, int fd_to_send) +{ + struct msghdr msg =3D { 0 }; + struct cmsghdr *cmsg; + char cmsg_buf[CMSG_SPACE(sizeof(int))]; + char dummy_data =3D 'F'; + struct iovec iov =3D { .iov_base =3D &dummy_data, .iov_len =3D 1 }; + + msg.msg_iov =3D &iov; + msg.msg_iovlen =3D 1; + msg.msg_control =3D cmsg_buf; + msg.msg_controllen =3D sizeof(cmsg_buf); + + cmsg =3D CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level =3D SOL_SOCKET; + cmsg->cmsg_type =3D SCM_RIGHTS; + cmsg->cmsg_len =3D CMSG_LEN(sizeof(int)); + + memcpy(CMSG_DATA(cmsg), &fd_to_send, sizeof(int)); + + return sendmsg(socket_fd, &msg, 0) < 0 ? -1 : 0; +} + +/* Helper function to receive FD via SCM_RIGHTS */ +static int recv_fd_via_socket(int socket_fd) +{ + struct msghdr msg =3D { 0 }; + struct cmsghdr *cmsg; + char cmsg_buf[CMSG_SPACE(sizeof(int))]; + char dummy_data; + struct iovec iov =3D { .iov_base =3D &dummy_data, .iov_len =3D 1 }; + int received_fd =3D -1; + + msg.msg_iov =3D &iov; + msg.msg_iovlen =3D 1; + msg.msg_control =3D cmsg_buf; + msg.msg_controllen =3D sizeof(cmsg_buf); + + if (recvmsg(socket_fd, &msg, 0) < 0) + return -1; + + for (cmsg =3D CMSG_FIRSTHDR(&msg); cmsg; cmsg =3D CMSG_NXTHDR(&msg, cmsg)= ) { + if (cmsg->cmsg_level =3D=3D SOL_SOCKET && + cmsg->cmsg_type =3D=3D SCM_RIGHTS) { + memcpy(&received_fd, CMSG_DATA(cmsg), sizeof(int)); + break; + } + } + + return received_fd; +} + +static inline bool has_cap_sys_admin(void) +{ + cap_t caps =3D cap_get_proc(); + + if (!caps) + return false; + + cap_flag_value_t cap_val; + bool has_cap =3D (cap_get_flag(caps, CAP_SYS_ADMIN, CAP_EFFECTIVE, + &cap_val) =3D=3D 0) && + (cap_val =3D=3D CAP_SET); + + cap_free(caps); + return has_cap; +} + +/* + * Switch to non-root user and clear all capabilities + */ +static inline bool drop_all_privs(struct __test_metadata *_metadata) +{ + /* Drop supplementary groups */ + ASSERT_EQ(setgroups(0, NULL), 0); + + /* Switch to non-root user */ + ASSERT_EQ(setgid(1000), 0); + ASSERT_EQ(setuid(1000), 0); + + /* Clear all capabilities */ + cap_t empty =3D cap_init(); + + ASSERT_NE(empty, NULL); + ASSERT_EQ(cap_set_proc(empty), 0); + cap_free(empty); + + /* Prevent privilege regain */ + ASSERT_EQ(prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0); + + /* Verify privilege drop */ + ASSERT_FALSE(has_cap_sys_admin()); + return true; +} + +static inline int get_legacy_tiocsti_setting(struct __test_metadata *_meta= data) +{ + FILE *fp; + int value =3D -1; + + fp =3D fopen("/proc/sys/dev/tty/legacy_tiocsti", "r"); + if (!fp) { + /* legacy_tiocsti sysctl not available (kernel < 6.2) */ + return -1; + } + + if (fscanf(fp, "%d", &value) =3D=3D 1 && fclose(fp) =3D=3D 0) { + if (value < 0 || value > 1) + value =3D -1; /* Invalid value */ + } else { + value =3D -1; /* Failed to parse */ + } + + return value; +} + +static inline bool set_legacy_tiocsti_setting(struct __test_metadata *_met= adata, + int value) +{ + FILE *fp; + bool success =3D false; + + /* Sanity-check the value */ + ASSERT_GE(value, 0); + ASSERT_LE(value, 1); + + /* + * Try to open for writing; if we lack permission, return false so + * the test harness will skip variants that need to change it + */ + fp =3D fopen("/proc/sys/dev/tty/legacy_tiocsti", "w"); + if (!fp) + return false; + + /* Write the new setting */ + if (fprintf(fp, "%d\n", value) > 0 && fclose(fp) =3D=3D 0) + success =3D true; + else + TH_LOG("Failed to write legacy_tiocsti: %s", strerror(errno)); + + return success; +} + +/* + * TIOCSTI injection test function + * @tty_fd: TTY slave file descriptor to test TIOCSTI on + * Returns: 0 on success, -errno on failure + */ +static inline int test_tiocsti_injection(struct __test_metadata *_metadata, + int tty_fd) +{ + int ret; + char inject_char =3D 'V'; + + errno =3D 0; + ret =3D ioctl(tty_fd, TIOCSTI, &inject_char); + return ret =3D=3D 0 ? 0 : -errno; +} + +/* + * Child process: test TIOCSTI directly with capability/controlling + * terminal setup + */ +static void run_basic_tiocsti_test(struct __test_metadata *_metadata, + FIXTURE_DATA(tiocsti) * self, + const FIXTURE_VARIANT(tiocsti) * variant) +{ + /* Handle capability requirements */ + if (self->initial_cap_sys_admin && !variant->requires_cap) + ASSERT_TRUE(drop_all_privs(_metadata)); + + if (variant->controlling_tty) { + /* + * Create new session and set PTY as + * controlling terminal + */ + pid_t sid =3D setsid(); + + ASSERT_GE(sid, 0); + ASSERT_EQ(ioctl(self->pty_slave_fd, TIOCSCTTY, 0), 0); + } + + /* + * Validate test environment setup and verify final + * capability state matches expectation + * after potential drop. + */ + ASSERT_TRUE(self->has_pty); + ASSERT_EQ(has_cap_sys_admin(), variant->requires_cap); + + /* Test TIOCSTI and validate result */ + int result =3D test_tiocsti_injection(_metadata, self->pty_slave_fd); + + /* Check against expected result from variant */ + EXPECT_EQ(result, variant->expected_success); + _exit(0); +} + +/* + * Child process: create PTY and then pass FD to parent via SCM_RIGHTS + */ +static void run_fdpass_tiocsti_test(struct __test_metadata *_metadata, + const FIXTURE_VARIANT(tiocsti) * variant, + int sockfd) +{ + signal(SIGHUP, SIG_IGN); + + /* Handle privilege dropping */ + if (!variant->requires_cap && has_cap_sys_admin()) + ASSERT_TRUE(drop_all_privs(_metadata)); + + /* Create child's PTY */ + int child_master_fd, child_slave_fd; + + ASSERT_EQ(openpty(&child_master_fd, &child_slave_fd, NULL, NULL, NULL), + 0); + + if (variant->controlling_tty) { + pid_t sid =3D setsid(); + + ASSERT_GE(sid, 0); + ASSERT_EQ(ioctl(child_slave_fd, TIOCSCTTY, 0), 0); + } + + /* Test child's direct TIOCSTI for reference */ + int direct_result =3D test_tiocsti_injection(_metadata, child_slave_fd); + + EXPECT_EQ(direct_result, variant->expected_success); + + /* Send FD to parent */ + ASSERT_EQ(send_fd_via_socket(sockfd, child_slave_fd), 0); + + /* Wait for parent completion signal */ + char sync_byte; + ssize_t bytes_read =3D read(sockfd, &sync_byte, 1); + + ASSERT_EQ(bytes_read, 1); + + close(child_master_fd); + close(child_slave_fd); + close(sockfd); + _exit(0); +} + +FIXTURE_SETUP(tiocsti) +{ + /* Create PTY pair for basic tests */ + self->has_pty =3D (openpty(&self->pty_master_fd, &self->pty_slave_fd, + NULL, NULL, NULL) =3D=3D 0); + if (!self->has_pty) { + self->pty_master_fd =3D -1; + self->pty_slave_fd =3D -1; + } + + self->initial_cap_sys_admin =3D has_cap_sys_admin(); + self->original_legacy_tiocsti_setting =3D + get_legacy_tiocsti_setting(_metadata); + + if (self->original_legacy_tiocsti_setting < 0) + SKIP(return, + "legacy_tiocsti sysctl not available (kernel < 6.2)"); + + /* Common skip conditions */ + if (variant->test_type =3D=3D TEST_PTY_TIOCSTI_BASIC && !self->has_pty) + SKIP(return, "PTY not available for controlling terminal test"); + + if (variant->test_type =3D=3D TEST_PTY_TIOCSTI_FD_PASSING && + !self->initial_cap_sys_admin) + SKIP(return, "FD Pass tests require CAP_SYS_ADMIN"); + + if (variant->requires_cap && !self->initial_cap_sys_admin) + SKIP(return, "Test requires initial CAP_SYS_ADMIN"); + + /* Test if we can modify the sysctl (requires appropriate privileges) */ + self->can_modify_sysctl =3D set_legacy_tiocsti_setting( + _metadata, self->original_legacy_tiocsti_setting); + + /* Sysctl setup based on variant */ + if (self->can_modify_sysctl && + self->original_legacy_tiocsti_setting !=3D variant->legacy_tiocsti) { + if (!set_legacy_tiocsti_setting(_metadata, + variant->legacy_tiocsti)) + SKIP(return, "Failed to set legacy_tiocsti sysctl"); + + } else if (!self->can_modify_sysctl && + self->original_legacy_tiocsti_setting !=3D + variant->legacy_tiocsti) + SKIP(return, "legacy_tiocsti setting mismatch"); +} + +FIXTURE_TEARDOWN(tiocsti) +{ + /* + * Backup restoration - + * each test should restore its own sysctl changes + */ + if (self->can_modify_sysctl) { + int current_value =3D get_legacy_tiocsti_setting(_metadata); + + if (current_value !=3D self->original_legacy_tiocsti_setting) { + TH_LOG("Backup: Restoring legacy_tiocsti from %d to %d", + current_value, + self->original_legacy_tiocsti_setting); + set_legacy_tiocsti_setting( + _metadata, + self->original_legacy_tiocsti_setting); + } + } + + if (self->has_pty) { + if (self->pty_master_fd >=3D 0) + close(self->pty_master_fd); + if (self->pty_slave_fd >=3D 0) + close(self->pty_slave_fd); + } +} + +TEST_F(tiocsti, test) +{ + int status; + pid_t child_pid; + + if (variant->test_type =3D=3D TEST_PTY_TIOCSTI_BASIC) { + /* =3D=3D=3D=3D=3D BASIC TIOCSTI TEST =3D=3D=3D=3D=3D */ + child_pid =3D fork(); + ASSERT_GE(child_pid, 0); + + /* Perform the actual test in the child process */ + if (child_pid =3D=3D 0) + run_basic_tiocsti_test(_metadata, self, variant); + + } else { + /* =3D=3D=3D=3D=3D FD PASSING SECURITY TEST =3D=3D=3D=3D=3D */ + int sockpair[2]; + + ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair), 0); + + child_pid =3D fork(); + ASSERT_GE(child_pid, 0); + + if (child_pid =3D=3D 0) { + /* Child process - create PTY and send FD */ + close(sockpair[0]); + run_fdpass_tiocsti_test(_metadata, variant, + sockpair[1]); + } + + /* Parent process - receive FD and test TIOCSTI */ + close(sockpair[1]); + + int received_fd =3D recv_fd_via_socket(sockpair[0]); + + ASSERT_GE(received_fd, 0); + + bool parent_has_cap =3D self->initial_cap_sys_admin; + + TH_LOG("=3D=3D=3D TIOCSTI FD Passing Test Context =3D=3D=3D"); + TH_LOG("legacy_tiocsti: %d, Parent CAP_SYS_ADMIN: %s, Child: %s", + variant->legacy_tiocsti, parent_has_cap ? "yes" : "no", + variant->requires_cap ? "kept" : "dropped"); + + /* SECURITY TEST: Try TIOCSTI with FD opened by child */ + int result =3D test_tiocsti_injection(_metadata, received_fd); + + /* Log security concern if demonstrated */ + if (result =3D=3D 0 && !variant->requires_cap) { + TH_LOG("*** SECURITY CONCERN DEMONSTRATED ***"); + TH_LOG("Privileged parent can use TIOCSTI on FD from unprivileged child= "); + TH_LOG("This shows current process credentials are used, not opener cre= dentials"); + } + + EXPECT_EQ(result, variant->expected_success) + { + TH_LOG("FD passing: expected error %d, got %d", + variant->expected_success, result); + } + + /* Signal child completion */ + char sync_byte =3D 'D'; + ssize_t bytes_written =3D write(sockpair[0], &sync_byte, 1); + + ASSERT_EQ(bytes_written, 1); + + close(received_fd); + close(sockpair[0]); + } + + /* Common child process cleanup for both test types */ + ASSERT_EQ(waitpid(child_pid, &status, 0), child_pid); + + if (WIFSIGNALED(status)) { + TH_LOG("Child terminated by signal %d", WTERMSIG(status)); + ASSERT_FALSE(WIFSIGNALED(status)) + { + TH_LOG("Child process failed assertion"); + } + } else { + EXPECT_EQ(WEXITSTATUS(status), 0); + } +} + +TEST_HARNESS_MAIN --- base-commit: e6b9dce0aeeb91dfc0974ab87f02454e24566182 change-id: 20250618-toicsti-bug-7822b8e94a32 Best regards, --=20 Abhinav Saxena